Python String Methods
Table of Contents
In the last lesson, we learned about Python String Basics. Now letβs use built-in string methods to change and clean text.
Letβs Talk About Tools for Strings
We have a string. Maybe it is a name. Maybe it is a sentence. Maybe it is something a user typed.
Now we want to do something with it. Change it to uppercase. Remove extra spaces. Replace a word. Split it into pieces.
That is what string methods are for.
A method is like a function, but it belongs to a specific object. For strings, there are many built-in methods. They make working with text much easier.
How to Use a String Method in Python
We write the string. Then a dot. Then the method name. Then parentheses.
name = "alex"print(name.upper())Output
ALEXSee? name.upper() takes the string "alex" and returns a new string "ALEX".
The original string does not change. Letβs remember, strings are immutable. The method returns a new string.
Changing Case in Python Strings
upper()
Makes everything uppercase.
name = "alex"print(name.upper())Output
ALEXlower()
Makes everything lowercase.
name = "ALEX"print(name.lower())Output
alexcapitalize()
Capitalizes the first letter. Makes the rest lowercase.
name = "alex smith"print(name.capitalize())Output
Alex smithtitle()
Capitalizes the first letter of each word.
name = "alex smith"print(name.title())Output
Alex Smithswapcase()
Swaps uppercase to lowercase and vice versa.
text = "Hello World"print(text.swapcase())Output
hELLO wORLDRemoving Spaces in Python Strings
strip()
Removes spaces from both ends.
text = " hello "print(text.strip())Output
helloThis is very useful when we get input from a user. They might accidentally add spaces. strip() cleans it up.
lstrip()
Removes spaces from the left side only.
text = " hello "print(text.lstrip())Output
hellorstrip()
Removes spaces from the right side only.
text = " hello "print(text.rstrip())Output
helloFinding and Counting in Python Strings
find()
Finds the position of a substring. Returns the index. If not found, returns -1.
text = "Hello, world!"print(text.find("world"))Output
7print(text.find("python"))Output
-1index()
Same as find(), but gives an error if not found.
text = "Hello, world!"print(text.index("world"))Output
7print(text.index("python"))Output
ValueError: substring not foundLetβs use find() if we want a safe check. Use index() if we are sure it exists.
count()
Counts how many times something appears.
text = "banana"print(text.count("a"))Output
3Replacing in Python Strings
replace()
Replaces a part of the string with something else.
text = "Hello, world!"print(text.replace("world", "Python"))Output
Hello, Python!We can also limit how many replacements to make.
text = "one one one"print(text.replace("one", "two", 2))Output
two two oneSplitting and Joining in Python Strings
split()
Splits a string into a list. We give it a separator.
text = "apple,banana,orange"print(text.split(","))Output
['apple', 'banana', 'orange']If we do not give a separator, it splits on spaces.
text = "Hello world how are you"print(text.split())Output
['Hello', 'world', 'how', 'are', 'you']join()
Joins a list of strings into one string. We give it a separator.
words = ["Hello", "world"]print(" ".join(words))Output
Hello worldwords = ["apple", "banana", "orange"]print(", ".join(words))Output
apple, banana, orangeNotice the order. The separator comes first. Then .join(). Then the list.
That is a bit backwards from how we might think. But we get used to it.
Checking Content in Python Strings
startswith()
Checks if the string starts with something.
text = "Hello, world!"print(text.startswith("Hello"))Output
Trueendswith()
Checks if the string ends with something.
text = "Hello, world!"print(text.endswith("!"))Output
Trueisalpha()
Checks if all characters are letters.
print("Hello".isalpha()) # Trueprint("Hello123".isalpha()) # Falseisdigit()
Checks if all characters are digits.
print("12345".isdigit()) # Trueprint("123a".isdigit()) # Falseisalnum()
Checks if all characters are letters or digits.
print("Hello123".isalnum()) # Trueprint("Hello 123".isalnum()) # False (space is not allowed)isspace()
Checks if all characters are spaces.
print(" ".isspace()) # Trueprint(" a ".isspace()) # Falseisupper()
Checks if all letters are uppercase.
print("HELLO".isupper()) # Trueprint("Hello".isupper()) # Falseislower()
Checks if all letters are lowercase.
print("hello".islower()) # Trueprint("Hello".islower()) # FalsePython String Methods: A Real-Life Example
Letβs clean up user input.
name = input("Enter your name: ")name = name.strip().title()print(f"Hello, {name}!")If the user types alex smith , the output is:
Hello, Alex Smith!See how strip() removed the extra spaces, and title() capitalized each word? That is a common pattern.
Another Example β Checking a Password
password = input("Enter a password: ")
if len(password) < 8: print("Password must be at least 8 characters")elif not any(c.isdigit() for c in password): print("Password must contain at least one digit")elif not any(c.isupper() for c in password): print("Password must contain at least one uppercase letter")else: print("Password is strong")That uses several string methods and a bit of logic.
Chaining Methods in Python
We can chain methods together.
text = " HELLO WORLD "print(text.strip().lower().title())Output
Hello WorldIt works from left to right. First strip(), then lower(), then title().
That is very convenient. But letβs not chain too many. It becomes hard to read.
Common Mistakes with Python String Methods
Mistake 1: Thinking Methods Change the Original String
name = "alex"name.upper()print(name)Output
alexBecause upper() returns a new string. It does not change the original. We have to assign it.
So what do we do? We assign the result.
name = name.upper()print(name)Output
ALEXMistake 2: Using the Wrong Method Name
name = "alex"print(name.toupper()) # Error!So what do we do? We use the correct method.
print(name.upper())Mistake 3: Forgetting Parentheses
name = "alex"print(name.upper) # This prints the method, not the resultOutput
<built-in method upper of str object at 0x...>So what do we do? We add the parentheses.
print(name.upper())Mistake 4: Using replace Without Assigning
text = "Hello"text.replace("H", "J")print(text)Output
HelloSo what do we do? We assign the result.
text = text.replace("H", "J")print(text)Output
JelloNext, we will learn about Python String Slicing and extract selected parts of a string.