Beginner   Chapter 36 · 30 min read · Module 3: Python Strings

String Methods

Learning objectives
  • After this chapter you can change the case of text with upper, lower, title and capitalize.
  • You can clean text with strip, and replace parts of it with replace.
  • You can search with find, index, count, startswith and endswith.
  • You can split text into a list and join a list back into text.
  • You can use test methods such as isdigit and isalpha and know that methods return new strings.

Strings are everywhere in programs: names, messages, file paths, web addresses. Python gives every string a large set of built-in tools called methods. A method is a function that belongs to the string and is called with a dot, like text.upper().

Learning the common methods saves a lot of work. Instead of writing loops to change case or find a word, you call one short method. Most of them are named clearly, so the code almost explains itself.

In this chapter you will meet the methods that you will use again and again. A very important idea runs through all of them: strings cannot be changed, so every method returns a new string and leaves the original untouched.

Changing case

Case methods change how letters look. upper() makes every letter capital and lower() makes every letter small. title() capitalises the first letter of each word, while capitalize() only changes the first letter of the whole string and makes the rest lower case. swapcase() flips each letter. For comparing text without caring about case, casefold() is a stronger version of lower() that also handles special letters from other languages.

Method: a function that belongs to an object and is called with dot notation, such as text.upper()
Example 1: case methods
s = "hello PYTHON world"
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
print(s.swapcase())
print(s)
HELLO PYTHON WORLD hello python world Hello Python World Hello python world HELLO python WORLD hello PYTHON world

The last line prints the original string and it has not changed. This proves that methods return new strings. If you want to keep the result, store it in a variable, for example s = s.upper().

Trimming and replacing

Text from users often has extra spaces or new lines at the ends. strip() removes white space from both ends, lstrip() from the left and rstrip() from the right. You can also pass a string of characters to remove, such as strip('-'). The replace(old, new) method swaps every occurrence of one piece of text for another, and an optional third number limits how many replacements are made.

Example 2: strip and replace
raw = "   --  spaced out  --   "
print(repr(raw.strip()))
print(repr(raw.strip().strip('-').strip()))
print("banana".replace("a", "o"))
print("banana".replace("a", "o", 2))
'-- spaced out --' 'spaced out' bonono bonona

Using repr() in the example shows the exact text, including the quotes, so you can see that all spaces at the ends have gone. Remember that strip('-') removes any of the listed characters from the ends, not a whole word, and it stops at the first character that is not in the list.

Searching inside text

To look for a piece of text, use find(), which gives the index of the first match or -1 if there is none. index() does the same but raises a ValueError if the text is missing, which is useful when a missing value is a real problem. count() tells how many times a piece appears, and startswith() and endswith() return True or False. Use in when you only need a yes or no answer.

Example 3: searching
s = "to be or not to be"
print(s.find("be"))
print(s.find("be", 4))
print(s.find("xyz"))
print(s.count("to"))
print(s.startswith("to"), s.endswith("be"))
print("not" in s)
3 16 -1 2 True True True
MethodWhat it doesExample result
upper()all capitals'ABC'
strip()trim ends'a b'
find(x)first index or -13
replace(a, b)swap text'bob'
split(sep)text to list['a', 'b']
join(list)list to text'a-b'
isdigit()only digits?True
zfill(n)pad with zeros'007'

Splitting and joining

split() cuts a string into a list. With no argument it splits on any run of white space, which is perfect for words. With an argument such as a comma, it cuts at every comma. join() goes the other way: it is called on the separator and takes a list of strings. This reads backwards for beginners, but remember it as separator.join(pieces). splitlines() splits at line ends and partition() splits once into three parts.

Example 4: split and join
line = "red, green ,blue"
parts = [p.strip() for p in line.split(",")]
print(parts)
print(" | ".join(parts))
print("one  two   three".split())
print("key=value=x".partition("="))
print("a\nb\nc".splitlines())
['red', 'green', 'blue'] red | green | blue ['one', 'two', 'three'] ('key', '=', 'value=x') ['a', 'b', 'c']

Testing the content

Test methods answer yes or no questions. isdigit() is true when all characters are digits, isalpha() when all are letters, isalnum() for letters or digits, isspace() for white space, and isupper() or islower() for case. They return False for an empty string. Use them to check user input before converting it with int().

Example 5: tests and padding
for text in ["2024", "abc", "ab12", "", "  "]:
    print(repr(text), text.isdigit(), text.isalpha(), text.isalnum(), text.isspace())
print("7".zfill(3), "hi".center(6, "*"), "hi".ljust(5, ".") + "|")
'2024' True False True False 'abc' False True True False 'ab12' False False True False '' False False False False ' ' False False False True 007 **hi** hi...|
Methods can be chained, as in text.strip().lower().title(). Each call works on the result of the one before it, from left to right.

Why are there so many methods? Because text work is so common. You do not need to memorise all of them. Learn the ones in this chapter well, and use help(str) or the Python documentation when you need something rarer. When you are unsure, try the method on a small example in the interpreter and look at the result.

Python syntax

Syntax
text.upper()  # also lower(), title(), capitalize()
Syntax
text.strip()  # also lstrip(), rstrip()
Syntax
text.replace(old, new[, count])
Syntax
text.find(sub[, start])  # -1 if missing
Syntax
text.split(sep) / sep.join(list)
Syntax
text.startswith(prefix) / text.endswith(suffix)

Real-world applications

  • Cleaning user input before storing it
  • Searching log files for error words
  • Splitting CSV style lines into fields
  • Normalising names and e-mail addresses
  • Validating that input is digits or letters

Common mistakes

Mistake: Calling text.upper() and expecting text itself to change
Fix: Strings are immutable; assign the result: text = text.upper().
Mistake: Using find() result as a boolean, such as if s.find('a'):
Fix: find returns -1 when missing and 0 when found at the start; compare with -1 or use the in operator.
Mistake: Writing list.join(',') instead of ','.join(list)
Fix: join is a string method called on the separator.
Mistake: Using join on a list of numbers
Fix: Convert items to strings first, for example ','.join(str(n) for n in nums).
Mistake: Thinking strip('ab') removes the word ab only
Fix: It removes any of the characters a or b from the ends; use removeprefix or removesuffix for whole text.

Important tips

  • Chain methods for short clean-up lines.
  • Use casefold() when comparing text from users.
  • Use removeprefix() and removesuffix() (Python 3.9+) to cut known text.
  • Check input with isdigit() before int().

Key points summary

  • String methods return new strings.
  • find returns -1 but index raises ValueError.
  • split makes a list and join makes a string.
  • Test methods return True or False.
  • Chaining works from left to right.

Exam and interview points

  • Methods on str never modify in place.
  • split() without arguments ignores repeated spaces; split(' ') does not.
  • '' .isdigit() is False.
  • count counts non-overlapping matches.

Quick revision

  • upper lower title capitalize swapcase
  • strip lstrip rstrip
  • find index count replace
  • split join partition splitlines
  • isdigit isalpha isalnum isspace

Frequently asked questions

Do string methods change the original string?

No. Strings are immutable, so each method gives back a new string.

What is the difference between find and index?

find returns -1 when the text is missing, while index raises a ValueError.

Why does join look backwards?

The separator is the object, so you write separator.join(items). The method works on any iterable of strings.

How do I split only once?

Pass a second argument, such as text.split(',', 1), or use partition.

Does isdigit work on negative numbers or decimals?

No. The minus sign and the point are not digits, so '-5' and '2.5' give False.

Practise this chapter

23 practice questions Take the chapter quiz

Related chapters