0%

7- String Methods

Strings come with built-in magic. Methods that change case, strip whitespace, search for words, and more. No loops needed.

You have a string. You want to make it uppercase. Or lowercase. Or remove extra spaces from the beginning and end. Or count how many times a certain word appears. Or replace one word with another. You could write loops and conditions to do all of this manually. But Python gives you a better way. String methods. A method is a function that belongs to an object. For strings, methods are called using dot notation: string.method(). Each method performs a specific operation and returns a new string (remember, strings are immutable).

🕯️ 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.

Changing Case
These methods transform the case of letters in a string. They are useful for standardizing user input, comparing strings case-insensitively, or formatting text.
MethodWhat It DoesExampleResult
.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

💡 Use .lower() or .upper() for case-insensitive comparisons. Convert both strings to the same case before comparing: user_input.lower() == “yes”.lower().
Checking String Content (Boolean Methods)
These methods return True or False. They help you inspect what kind of characters a string contains.
MethodReturns 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”)

⚠️ .isdigit() returns False for negative numbers or decimals because the minus sign and decimal point are not digits. Use .isdecimal() for stricter digit checking or handle validation manually.
Stripping Whitespace
User input often comes with extra spaces at the beginning, end, or both. These methods remove unwanted whitespace.
MethodWhat It DoesExampleResult
.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”

💡 Always use .strip() on user input before processing. It prevents bugs caused by accidental spaces. A simple name.strip() can save hours of debugging.
Finding and Searching
These methods help you locate substrings within a string.
MethodWhat It DoesExampleResult
.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.

Replacing Parts of a String
The .replace() method replaces all occurrences of a substring with another substring.

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

⚠️ .replace() replaces all occurrences by default. If you only want to replace the first occurrence, use the count parameter: text.replace(“old”, “new”, 1).
Splitting Strings into Lists
The .split() method breaks a string into a list of substrings. It is incredibly useful for parsing data.

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’]

💡 The opposite of .split() is .join(). It joins a list of strings into one string: “,”.join([“apple”, “banana”, “cherry”]) returns “apple,banana,cherry”.
Joining Strings
The .join() method is called on a separator and takes an iterable (like a list) of strings to join together.

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.

Checking Start and End
These methods check if a string starts or ends with a specific substring.

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

Common Mistakes with String Methods
  • 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)
Check Your Understanding
  • 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.

Related posts