← Core Concepts
Concept
String methods — common string operations
Essential methods for working with strings.
Case conversion
text = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
print(text.title()) # "Hello World"
print(text.capitalize()) # "Hello world"
Checking content
text = "Hello123"
print(text.isalpha()) # False (has numbers)
print(text.isdigit()) # False (has letters)
print(text.isalnum()) # True (letters and numbers)
print(text.startswith("Hello")) # True
print(text.endswith("123")) # True
Splitting and joining
# Split into list:
text = "apple,banana,cherry"
fruits = text.split(",") # ['apple', 'banana', 'cherry']
# Join list into string:
fruits = ['apple', 'banana', 'cherry']
text = ",".join(fruits) # "apple,banana,cherry"
Stripping whitespace
text = " hello world "
print(text.strip()) # "hello world" (both sides)
print(text.lstrip()) # "hello world " (left only)
print(text.rstrip()) # " hello world" (right only)
Finding and replacing
text = "Hello World"
# Find position:
print(text.find("World")) # 6
print(text.find("Python")) # -1 (not found)
# Replace:
new_text = text.replace("World", "Python")
print(new_text) # "Hello Python"
Formatting
name = "Alice"
age = 30
# f-strings (Python 3.6+):
message = f"My name is {name} and I'm {age}"
# .format():
message = "My name is {} and I'm {}".format(name, age)