🕯️ Magic Note
String methods do not change the original string. They create and return a brand new string. This is why you often see text = text.upper() – you are reassigning the result back to the variable.
| Method | What It Does | Example | Result |
|---|---|---|---|
| .upper() | All letters to uppercase | “hello”.upper() | “HELLO” |
| .lower() | All letters to lowercase | “HELLO”.lower() | “hello” |
| .capitalize() | First letter uppercase, rest lowercase | “hello WORLD”.capitalize() | “Hello world” |
| .title() | First letter of each word uppercase | “hello world”.title() | “Hello World” |
| .swapcase() | Swaps uppercase to lowercase and vice versa | “Hello World”.swapcase() | “hELLO wORLD” |
Python
text = “python is MAGICAL”
print(text.upper()) # PYTHON IS MAGICAL
print(text.lower()) # python is magical
print(text.capitalize()) # Python is magical
print(text.title()) # Python Is Magical
print(text.swapcase()) # PYTHON IS magical
# Original string remains unchanged
print(text) # python is MAGICAL
| Method | Returns True If... | Example |
|---|---|---|
| .isalpha() | All characters are letters (a-z, A-Z) | “hello”.isalpha() → True, “hello123”.isalpha() → False |
| .isdigit() | All characters are digits (0-9) | “123”.isdigit() → True, “12.3”.isdigit() → False |
| .isalnum() | All characters are letters or digits | “hello123”.isalnum() → True, “hello 123”.isalnum() → False |
| .isspace() | All characters are whitespace (space, tab, newline) | ” “.isspace() → True |
| .isupper() | All letters are uppercase (ignores non-letters) | “HELLO”.isupper() → True |
| .islower() | All letters are lowercase | “hello”.islower() → True |
| .istitle() | String is in title case (each word starts with uppercase) | “Hello World”.istitle() → True |
Python
# Checking string content
print(“Python123”.isalnum()) # True (letters and digits)
print(“Python123”.isalpha()) # False (contains digits)
print(“42”.isdigit()) # True
print(” “.isspace()) # True
# Useful for input validation
user_age = input(“Enter your age: “)
if user_age.isdigit():
print(f”You are {user_age} years old”)
else:
print(“Please enter a valid number”)
| Method | What It Does | Example | Result |
|---|---|---|---|
| .strip() | Removes whitespace from both ends | ” hello “.strip() | “hello” |
| .lstrip() | Removes whitespace from left (beginning) | ” hello “.lstrip() | “hello ” |
| .rstrip() | Removes whitespace from right (end) | ” hello “.rstrip() | ” hello” |
Python
messy = ” hello world “
print(messy.strip()) # “hello world” (no spaces)
print(messy.lstrip()) # “hello world “
print(messy.rstrip()) # ” hello world”
# These methods can also remove specific characters
url = “///feloriya.co///”
print(url.strip(“/”)) # “feloriya.co”
| Method | What It Does | Example | Result |
|---|---|---|---|
| .find(sub) | Returns the lowest index where sub is found, or -1 if not found | “hello”.find(“l”) | 2 |
| .rfind(sub) | Returns the highest index where sub is found (searches from right) | “hello”.rfind(“l”) | 3 |
| .index(sub) | Same as find but raises ValueError if not found | “hello”.index(“l”) | 2 |
| .count(sub) | Returns the number of non-overlapping occurrences of sub | “hello”.count(“l”) | 2 |
Python
text = “the magic of python magic”
print(text.find(“magic”)) # 4 (first occurrence)
print(text.rfind(“magic”)) # 20 (last occurrence)
print(text.count(“magic”)) # 2
print(text.find(“java”)) # -1 (not found)
# Using index (raises error if not found)
print(text.index(“magic”)) # 4
# print(text.index(“java”)) # ValueError: substring not found
🕯️ Magic Note
Use .find() when you are not sure if the substring exists (returns -1). Use .index() when you are certain it exists or want to catch the error explicitly. Most Python programmers prefer .find() for simplicity.
Python
text = “I love Java. Java is great.”
new_text = text.replace(“Java”, “Python”)
print(new_text) # I love Python. Python is great.
# You can limit the number of replacements
text2 = “one one one one”
print(text2.replace(“one”, “two”, 2)) # two two one one
Python
# Split by whitespace (default)
sentence = “Python is magical”
words = sentence.split()
print(words) # [‘Python’, ‘is’, ‘magical’]
# Split by specific character
data = “apple,banana,cherry”
fruits = data.split(“,”)
print(fruits) # [‘apple’, ‘banana’, ‘cherry’]
# Limit the number of splits
text = “one|two|three|four”
print(text.split(“|”, 2)) # [‘one’, ‘two’, ‘three|four’]
Python
words = [“Conjure”, “the”, “magic”]
sentence = ” “.join(words)
print(sentence) # Conjure the magic
path_parts = [“usr”, “local”, “bin”]
path = “/”.join(path_parts)
print(path) # usr/local/bin
# .join() is more efficient than + for many strings
result = “”.join([“a”, “b”, “c”]) # “abc”
🕯️ Magic Note
Use “”.join(list) instead of a loop with + for better performance. String concatenation in a loop creates many intermediate strings. .join() creates only one final string.
Python
filename = “script.py”
print(filename.startswith(“script”)) # True
print(filename.endswith(“.py”)) # True
print(filename.endswith(“.txt”)) # False
# Can check multiple possibilities with a tuple
print(filename.endswith((“.py”, “.txt”, “.md”))) # True
url = “https://feloriya.co”
print(url.startswith((“http://”, “https://”))) # True
- Forgetting that string methods return a new string (they do not modify the original)
- Chaining too many methods without checking intermediate results: s.strip().lower().replace(“a”, “b”)
- Using .find() and forgetting it returns -1 when not found (not False)
- Calling .split() without an argument expects whitespace. Use .split(“,”) for commas
- Assuming .isdigit() works for negative numbers or decimals (it does not)
- Using .index() when the substring might be missing (causes ValueError)
- How do you convert a string to uppercase?
- What is the difference between .find() and .index()?
- How do you remove extra spaces from the beginning and end of a string?
- What method would you use to check if a string contains only digits?
- Write code to split “a,b,c” into a list of three strings.
- What does “hello world”.title() return?
⚡ Whisper
String methods are the tools of a careful whisperer. You do not need to touch each letter yourself. You simply ask: make this louder. make this softer. find this word. remove these spaces. The string listens and gives you a new version of itself. The original remains untouched, like a memory you can always return to. Learn these methods one by one. Each is a small spell. Together they become a language of transformation.