Beginner Chapter 36 · 30 min read · Module 3: Python Strings
String Methods
- 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.
s = "hello PYTHON world"
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
print(s.swapcase())
print(s)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.
raw = " -- spaced out -- "
print(repr(raw.strip()))
print(repr(raw.strip().strip('-').strip()))
print("banana".replace("a", "o"))
print("banana".replace("a", "o", 2))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.
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)| Method | What it does | Example result |
|---|---|---|
| upper() | all capitals | 'ABC' |
| strip() | trim ends | 'a b' |
| find(x) | first index or -1 | 3 |
| 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.
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())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().
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, ".") + "|")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
text.upper() # also lower(), title(), capitalize()text.strip() # also lstrip(), rstrip()text.replace(old, new[, count])text.find(sub[, start]) # -1 if missingtext.split(sep) / sep.join(list)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
Fix: Strings are immutable; assign the result: text = text.upper().
Fix: find returns -1 when missing and 0 when found at the start; compare with -1 or use the in operator.
Fix: join is a string method called on the separator.
Fix: Convert items to strings first, for example ','.join(str(n) for n in nums).
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