String Methods

Published by Brayan K

Real-world data is messy: extra spaces, inconsistent casing, stray punctuation, values jammed together with commas. String methods are the cleanup crew — a built-in toolkit for searching, slicing, normalizing, and reshaping text.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Methods make new text; the string never changes

A method is a function that belongs to a value. You call it with a dot after the value, as in name.strip(), and each kind of value has its own: text has upper() and strip(), a list has append() and sort(). No string method changes the string it's called on, because a string can't be changed at all. The ones that make text give back new text, and if you don't store it, it's gone:

name = "  Ada Lovelace "
name.strip()
print(f"[{name}]")
name = name.strip()
print(f"[{name}]")

# ✅ Expected output:
# [  Ada Lovelace ]
# [Ada Lovelace]

The square brackets show where the spaces are. The first strip() made the text "Ada Lovelace" and nothing kept it; name = name.strip() keeps it. Lists and Collections showed the other side of the same rule: word[0] = "b" can't change one letter either.

Leave off the brackets and you get the method itself, not the text it makes, just as a function name without () in Functions was the function:

name = "ada"
print("Name: " + name.upper)

# ✅ Expected error:
# TypeError: can only concatenate str (not "builtin_function_or_method") to str

builtin_function_or_method is Python's name for a method such as upper that comes with Python. With the brackets, name.upper() is the text ADA.

Changing case

upper() and lower() change every letter. title() starts each word with a capital and capitalize() only the first letter of the text, and both make every other letter lower case:

text = "the QUICK brown Fox"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print("mcDONALD".capitalize())
print("don't stop".title())

# ✅ Expected output:
# THE QUICK BROWN FOX
# the quick brown fox
# The Quick Brown Fox
# The quick brown fox
# Mcdonald
# Don'T Stop

So capitalize() turns mcDONALD into Mcdonald, and title() treats the apostrophe in don't as the end of a word. Neither is safe on names that already have their capitals in the right places.

To compare text without caring about case, as Operators and Expressions suggested, lowercase both sides:

answer = "YES"
print(answer == "yes")
print(answer.lower() == "yes")

# ✅ Expected output:
# False
# True

== compares text exactly, capitals included. For languages with special rules, such as the German ß, casefold() goes further than lower(); Strings, Bytes & Unicode Encodings covers it.

Cleaning with strip() and replace()

strip() removes spaces, tabs and line breaks from both ends, and lstrip() and rstrip() from one end. Given some characters, it removes those instead. replace() swaps every match, or only as many as a third argument says. Each of these gives back text, so you can call the next method on the result straight away:

raw = "   [email protected]   "
print(f"[{raw.strip()}]")
print(raw.strip().lower())
print("###title###".strip("#"))
print("555-123-4567".replace("-", ""))
print("a-b-c".replace("-", "_", 1))

# ✅ Expected output:
# [[email protected]]
# [email protected]
# title
# 5551234567
# a_b-c

raw.strip().lower() reads left to right: strip, then lowercase the stripped text. The characters you give strip() are a set of single characters, not a word, which catches people out at the end of a file name:

filename = "report.txt"
print(filename.rstrip(".txt"))
print(filename.removesuffix(".txt"))
print(f"[{'  two  words  '.strip()}]")

# ✅ Expected output:
# repor
# report
# [two  words]

rstrip(".txt") keeps removing dots, t's and x's from the right until it meets a character that isn't one of them, so it takes the t of report too. removesuffix() removes that exact ending once, and removeprefix() does the same at the start; both need Python 3.9 or later. The last line shows that strip() only touches the ends: the two spaces in the middle stay.

Searching: in, startswith(), find() and index()

To ask whether text contains something, use in, from Operators and Expressions. startswith() and endswith() check the ends. find() gives the position of the first match, counting from 0, or -1 when there's none, and count() says how many times something appears:

email = "[email protected]"
print("@" in email)
print(email.startswith("ada"))
print(email.endswith(".com"))
print(email.find("@"))
print(email.find("zzz"))
print(email.count("a"))

# ✅ Expected output:
# True
# True
# True
# 3
# -1
# 3

A match at the very start is at position 0, which makes find() a poor yes-or-no test: 0 counts as false in an if, as Control Flow - If/Else showed, and -1, for no match, counts as true.

email = "[email protected]"
if email.find("ada"):
    print("has ada")
else:
    print("no ada?")
print(email.find("ada"))
print("ada" in email)

# ✅ Expected output:
# no ada?
# 0
# True

Use in for the question and find() only when you need the position. index() gives the position too, but stops the program when there's no match, which suits a match that should always be there:

email = "[email protected]"
print(email.index("@"))
print(email.index("#"))

# ✅ Expected output:
# 3

# ✅ Expected error:
# ValueError: substring not found

With a position in hand, slicing cuts out part of the text: email[:3] is everything before position 3. Slicing isn't a method, and Slicing Lists & Strings covers it.

split() and join(): text to a list and back

split() cuts text at a separator and gives back a list of the pieces. join() does the reverse. It's called on the separator, and given the list:

line = "apple,banana,cherry"
fruits = line.split(",")
print(fruits)
print(len(fruits))
print("-".join(fruits))

# ✅ Expected output:
# ['apple', 'banana', 'cherry']
# 3
# apple-banana-cherry

With no argument, split() cuts at every run of spaces, tabs or line breaks and never gives an empty piece. With " ", it cuts at every single space, so two spaces in a row leave an empty piece between them:

full = "Ada  Lovelace"
print(full.split(" "))
print(full.split())
print("a, b, c".split(","))
print(" ".join("  too   many    spaces ".split()))

# ✅ Expected output:
# ['Ada', '', 'Lovelace']
# ['Ada', 'Lovelace']
# ['a', ' b', ' c']
# too many spaces

Splitting at a comma keeps the space after it, so strip each piece or split at ", ". The last line is a common trick: split at the runs of spaces, then join the words with one space. Real CSV files can hold commas inside quoted values, which a plain split(",") cuts in the wrong place; Reading CSV & Excel Files uses the csv module for them.

Not every method gives back text. split() gives a list, find() and count() a number, and startswith() and the is…() methods True or False. So the next method in a chain has to be one that the result has:

parts = "a,b".split(",")
print(parts.upper())

# ✅ Expected error:
# AttributeError: 'list' object has no attribute 'upper'

The items in the list are text and have upper(); the list itself doesn't. For the same reason, ["a", "b"].join("-") stops with an AttributeError: join() belongs to the separator, not the list. And every item you join must already be text:

print("-".join([1, 2, 3]))

# ✅ Expected error:
# TypeError: sequence item 0: expected str instance, int found

map(str, ...), from Lambda Functions, turns each number into text first:

nums = [1, 2, 3]
print("-".join(map(str, nums)))

# ✅ Expected output:
# 1-2-3

The is…() methods check what text holds

Methods whose names start with is answer a yes-or-no question about every character:

print("12345".isdigit())
print("12.5".isdigit())
print("-5".isdigit())
print("abc".isalpha())
print("abc123".isalnum())
print("   ".isspace())
print("²".isdigit())

# ✅ Expected output:
# True
# False
# False
# True
# True
# True
# True

isdigit() is True only when every character is a digit, so a point or a minus sign makes it False. It isn't a promise that int() will work, though: the superscript ² counts as a digit, yet int("²") stops with a ValueError, while int() reads " 42", "-5" and "+5" without trouble, all of which isdigit() rejects. To find out whether text is a number, try the conversion and handle the error, as Exception Handling shows.

Practice: a name from an email address

Fill the three blanks with the values in the hint lines, in order: trim the spaces, cut the address at the @, and turn the dot into a space.

raw = "  [email protected] "
email = raw.___().lower()
user = email.split(___)[0]
print(email)
print(user.___(".", " ").title())

# 👉 replace ___ with strip
# 👉 replace ___ with "@"
# 👉 replace ___ with replace

# ✅ Expected output:
# [email protected]
# Ada Lovelace

On your own: tidy a list of tags

A form collected tags as one line of text: raw = " Python, data science,PYTHON , web ". Split it at the commas, strip and lowercase each tag, keep each tag only once, and print how many there are, then the tags joined with " | ": 3, then python | data science | web. Then compare with this solution:

raw = " Python, data science,PYTHON , web "
tags = []
for piece in raw.split(","):
    tag = piece.strip().lower()
    if tag not in tags:
        tags.append(tag)
print(len(tags))
print(" | ".join(tags))

# ✅ Expected output:
# 3
# python | data science | web

piece.strip().lower() cleans each piece in one line, and tag not in tags skips one already kept. Sets keep one of each value without that check.

Practice quiz

name = " Ada ", then name.strip(), then print(f"[{name}]"). What prints?

  • [Ada]
  • [ Ada ]
  • An error
  • [ Ada]

Answer: [ Ada ]. strip() made new text, but nothing stored it, so name still has its spaces.

What does "mcDONALD".capitalize() give?

  • McDonald
  • MCDONALD
  • Mcdonald
  • mcDONALD

Answer: Mcdonald. capitalize() makes the first letter a capital and every other letter lower case.

What does "report.txt".rstrip(".txt") give?

  • repor
  • report
  • report.
  • An error

Answer: repor. rstrip() removes any of the characters ., t and x from the right, including the t of report. removesuffix() removes the exact ending.

What does "Ada Lovelace".split(" ") give, with two spaces between the names?

  • ['Ada', 'Lovelace']
  • ['Ada Lovelace']
  • ['Ada', ' ', 'Lovelace']
  • ['Ada', '', 'Lovelace']

Answer: ['Ada', '', 'Lovelace']. split(" ") cuts at every single space, so two in a row leave an empty piece. split() with no argument wouldn't.

What does "[email protected]".find("ada") give?

  • -1
  • 0
  • 1
  • True

Answer: 0. The match starts at position 0, which counts as false in an if. Use in to ask whether it's there.

What does "-".join([1, 2, 3]) do?

  • It gives '1-2-3'
  • It gives '-1-2-3'
  • It gives [1, '-', 2, '-', 3]
  • It stops with TypeError: sequence item 0: expected str instance, int found

Answer: It stops with TypeError: sequence item 0: expected str instance, int found. join() needs text. Turn the numbers into text first, for example with map(str, ...).

What does "a,b".split(",").upper() do?

  • It gives ['A', 'B']
  • It gives 'A,B'
  • It stops with AttributeError: 'list' object has no attribute 'upper'
  • It gives ['a', 'b']

Answer: It stops with AttributeError: 'list' object has no attribute 'upper'. split() gives a list, and a list has no upper() method. Its items do.

What does "banana".replace("a", "o", 1) give?

  • bonana
  • bonono
  • banano
  • banana

Answer: bonana. The third argument limits how many matches are replaced, counting from the left.

Continue this course

Frequently asked questions

How do I reverse a string?

There's no reverse() method for text. Slicing does it: text[::-1] steps through the text backwards. Slicing Lists & Strings explains the three numbers a slice can take.

What's the difference between split() and splitlines()?

split() with no argument cuts at any run of spaces, tabs or line breaks. splitlines() cuts only at line breaks, whichever kind the text uses, so each line keeps its spaces. It's the one to use on text read from a file, line by line.

Can I remove all punctuation, or split at several characters at once?

replace() handles one specified piece of text at a time. str.translate() can remove a chosen set of characters using a translation table. For a pattern, or splitting at a comma or a semicolon, re.sub() and re.split() from Regular Expressions (re) are useful; choose the pattern carefully because punctuation includes more than commas and full stops.

Related lessons