Python String Methods

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

ALEX

See? 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

ALEX

lower()

Makes everything lowercase.

name = "ALEX"
print(name.lower())

Output

alex

capitalize()

Capitalizes the first letter. Makes the rest lowercase.

name = "alex smith"
print(name.capitalize())

Output

Alex smith

title()

Capitalizes the first letter of each word.

name = "alex smith"
print(name.title())

Output

Alex Smith

swapcase()

Swaps uppercase to lowercase and vice versa.

text = "Hello World"
print(text.swapcase())

Output

hELLO wORLD

Removing Spaces in Python Strings

strip()

Removes spaces from both ends.

text = " hello "
print(text.strip())

Output

hello

This 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

hello

rstrip()

Removes spaces from the right side only.

text = " hello "
print(text.rstrip())

Output

hello

Finding 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

7
print(text.find("python"))

Output

-1

index()

Same as find(), but gives an error if not found.

text = "Hello, world!"
print(text.index("world"))

Output

7
print(text.index("python"))

Output

ValueError: substring not found

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

3

Replacing 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 one

Splitting 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 world
words = ["apple", "banana", "orange"]
print(", ".join(words))

Output

apple, banana, orange

Notice 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

True

endswith()

Checks if the string ends with something.

text = "Hello, world!"
print(text.endswith("!"))

Output

True

isalpha()

Checks if all characters are letters.

print("Hello".isalpha()) # True
print("Hello123".isalpha()) # False

isdigit()

Checks if all characters are digits.

print("12345".isdigit()) # True
print("123a".isdigit()) # False

isalnum()

Checks if all characters are letters or digits.

print("Hello123".isalnum()) # True
print("Hello 123".isalnum()) # False (space is not allowed)

isspace()

Checks if all characters are spaces.

print(" ".isspace()) # True
print(" a ".isspace()) # False

isupper()

Checks if all letters are uppercase.

print("HELLO".isupper()) # True
print("Hello".isupper()) # False

islower()

Checks if all letters are lowercase.

print("hello".islower()) # True
print("Hello".islower()) # False

Python 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 World

It 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

alex

Because 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

ALEX

Mistake 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 result

Output

<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

Hello

So what do we do? We assign the result.

text = text.replace("H", "J")
print(text)

Output

Jello

Next, we will learn about Python String Slicing and extract selected parts of a string.