Python Module 2 – Values, variables, numbers and strings
Essential string methods for cleaning text
Clean and search text with Python's string methods (strip, split, join, replace, find, startswith, casefold) and avoid the traps in strip() and isdigit().
What you will learn
- Clean and split text with strip, split, join and replace
- Remove an exact prefix or suffix without the strip() trap
- Search with find, index, startswith, endswith and in
- Compare text without case using casefold()
- Choose between isdecimal(), isdigit(), isnumeric() and int()
Before you start
What you’ll learn · Before you start
What you will learn
- Clean and split text with strip, split, join and replace
- Remove an exact prefix or suffix without the strip() trap
- Search with find, index, startswith, endswith and in
- Compare text without case using casefold()
- Choose between isdecimal(), isdigit(), isnumeric() and int()
Before you start
On this page
Text that comes from people, files and web pages is rarely tidy. It has spaces at the ends, capitals in odd places,
commas with gaps after them and the occasional empty field. Strings come with dozens of
method: A function that belongs to a value and is called with a dot after it, such as text.strip(). String methods return a new string and leave the original as it was., functions you call with a dot after a string (text.strip()), and a handful of
them do most of the cleaning and searching that real programs need.
One rule from the previous lesson shapes how you use all of them: strings never change, so a method gives you a new
string and leaves the original alone. Keep the result (name = name.strip()), and chain methods when you need
several steps: raw.strip().casefold() strips first, then folds the case of the stripped copy. Below, you clean a
typed line step by step, search it without the classic find() trap, compare words whatever their case, test for
digits and change many characters in one pass.
strip(), split() and join() clean a line in three steps
Here is a line of comma-separated fruit names typed by a person, cleaned step by step:
raw = " Mango, apple ,BANANA,, kiwi \n"
# strip() removes spaces, tabs and line breaks from both ends.
print(repr(raw.strip()))
# split(",") cuts at every comma and keeps the empty field between ",,".
fields = raw.strip().split(",")
print(fields)
# Clean each field in turn and keep the ones that are not empty.
names = []
for field in fields:
name = field.strip().casefold()
if name:
names.append(name)
print(names)
# join() is the opposite of split(): one string, with the separator between the parts.
print(" | ".join(names))
# split() with no argument splits on any run of whitespace and drops empty parts.
print(" ".join(" too many \t spaces ".split())) Output
'Mango, apple ,BANANA,, kiwi' ['Mango', ' apple ', 'BANANA', '', ' kiwi'] ['mango', 'apple', 'banana', 'kiwi'] mango | apple | banana | kiwi too many spaces
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 clean_line.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
strip()removes whitespace: Characters that show as empty space, such as spaces, tabs and line breaks. strip() removes them from both ends, and split() with no argument splits on any run of them. (spaces, tabs, line breaks) from both ends;lstrip()andrstrip()do only the left or the right end. A line read from a file usually ends with\n, soline.rstrip("\n")orline.strip()is often the first thing a program does with it.split(",")cuts the string at every comma and returns a list of the pieces. It keeps empty pieces: two commas in a row give an empty string between them, which is right for a spreadsheet row with an empty cell, and which is why the loop skips fields that are empty after stripping.split()with no argument behaves differently: it splits on any run of whitespace and never returns empty pieces." ".join(text.split())is a quick way to collapse several spaces and tabs into one space.join()is called on the separator and given the pieces:" | ".join(names)puts" | "between them. The pieces must all be strings;", ".join([1, 2, 3])raisesTypeError, so convert numbers withstr()first.replace(old, new)replaces every match;replace(old, new, 1)replaces only the first.
Step through the heart of that cleaning on a shorter line. split(",") makes the list under fields, one cell per
field, and the loop keeps a field only if something is left of it after strip():
Program · clean_fields.py
raw = " Mango, apple ,,kiwi \n"
fields = raw.strip().split(",")
names = []
for field in fields:
name = field.strip()
if name:
names.append(name)
print(" | ".join(names)) Variables
- just taken by the loop
- changed in this step
- passed by the loop
- read next
- where the loop stopped
Printed so far
Nothing printed yetMango | apple | kiwi
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 21 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
raw = " Mango, apple ,,kiwi \n"setsrawto' Mango, apple ,,kiwi \n'. - Line 2.
fields = raw.strip().split(",")setsfieldsto['Mango', ' apple ', '', 'kiwi'].strip()took the space and the line break off the ends first. Thensplit(",")cut at every comma, so the two commas in a row left an empty field at position 2. - Line 3.
names = []makesnamesa list of 0 items. - Line 4.
for field in fields:takes the item at position 0 offields:fieldis'Mango'. - Line 5.
name = field.strip()setsnameto'Mango'. - Line 6.
nameis true (nameis'Mango'), so the block underif name:runs. - Line 7.
names.append(name)adds'Mango'to the end ofnames. - Line 4.
for field in fields:takes the item at position 1 offields:fieldis' apple '. - Line 5.
name = field.strip()setsnameto'apple'(it was'Mango'). - Line 6.
nameis true (nameis'apple'), so the block underif name:runs. - Line 7.
names.append(name)adds'apple'to the end ofnames. - Line 4.
for field in fields:takes the item at position 2 offields:fieldis''. - Line 5.
name = field.strip()setsnameto''(it was'apple'). - Line 6.
nameis false (nameis''), so Python skips the block underif name:. Key point This is why the loop needs itsif:split(",")keeps the empty field, and only the test keeps it out ofnames. - Line 4.
for field in fields:takes the item at position 3 offields:fieldis'kiwi'. - Line 5.
name = field.strip()setsnameto'kiwi'(it was''). - Line 6.
nameis true (nameis'kiwi'), so the block underif name:runs. - Line 7.
names.append(name)adds'kiwi'to the end ofnames. - Line 4.
for field in fields:finds no item at position 4 offields(it has 4 items), so the loop ends. - Line 8.
print(" | ".join(names))printsMango | apple | kiwi. That was the last line, so the program ends.join()is called on the separator and puts it between the three names that were kept.
Position 2 of fields is the empty string between the two commas. On that pass name is '', which counts as
false, so if name: skips it and names ends with three names. Press Edit, change name = field.strip() to
name = field and run it again: the spaces around apple come back in the output.
Checkpoint
Check: strip(), split() and join()
strip() removes a set of characters, not a word
The argument of strip() is not a word to remove. It is a set of characters, and strip() keeps removing any of
them from both ends until it meets a character that is not in the set:
site = "mocha.com"
print(site.strip(".com"))
print(site.removesuffix(".com"))
print("comic.com".strip(".com"), "comic.com".removesuffix(".com"))
print("notes.txt".removesuffix(".pdf")) Output
ha mocha i comic notes.txt
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 strip_or_removesuffix.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
"mocha.com".strip(".com") removes m, o and c from the front and .com from the end, and comic.com loses
almost everything. To remove an exact beginning or ending, use removeprefix() or removesuffix() (added in Python
3.9 by PEP 616). They remove it at most once, and return the string unchanged when it does not start or end that way.
The two methods answer different questions, as the program’s first lines show side by side:
| Aspect | strip(".com") |
removesuffix(".com") |
|---|---|---|
| Its argument | a set: ., c, o and m |
one exact ending |
| What it removes | any of them, at both ends, until another character | that ending, once, at the end only |
"mocha.com" |
'ha' |
'mocha' |
"comic.com" |
'i' |
'comic' |
Reach for strip() with an argument only when you mean a set of characters, such as line.strip(" \t*") for spaces,
tabs and stars around a heading.
Checkpoint
Check: strip() takes a set of characters
in answers yes or no, and find() answers where
The next program searches one line from a log in several ways, and its last line stops it on purpose:
line = "ERROR: disk full on /dev/sda1"
# in answers yes or no; it is the clearest test.
print("disk" in line, "DISK" in line)
# find() gives the position of the first match, or -1 when there is none.
print(line.find("disk"), line.find("cpu"))
# startswith() and endswith() take one text or a tuple of texts to try.
print(line.startswith("ERROR"), line.endswith(("sda1", "sdb1")))
print(line.count("s"), line.replace("disk", "drive"))
# A trap: a match at the very start is position 0, and 0 counts as false.
if line.find("ERROR"):
print("found it")
else:
print("not found? find() returned", line.find("ERROR"))
# index() is like find() but raises ValueError when there is no match.
print(line.index("cpu")) Output (exit status 1)
True False 7 -1 True True 2 ERROR: drive full on /dev/sda1 not found? find() returned 0
Printed as an error (standard error)
Traceback (most recent call last):
File "search.py", line 20, in <module>
print(line.index("cpu"))
~~~~~~~~~~^^^^^^^
ValueError: substring not found
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 search.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
"disk" in lineis the clearest way to ask whether one string contains another. Like every comparison of strings it is case-sensitive, so"DISK" in lineisFalse.find()returns the position where the match starts, or -1 when there is none. Use it when you need the position, for example to slice the text after it.index()does the same but raisesValueErrorwhen there is no match, as the last line of the program shows. Use it when a missing match means something is wrong.startswith()andendswith()check the beginning and the end, and accept a tuple of possibilities:name.endswith((".jpg", ".png")).count()counts matches that do not overlap.
The second and third points meet in a trap. Step through it on its own and watch which way the if goes:
Program · find_trap.py
line = "ERROR: disk full"
where = line.find("ERROR")
if where:
print("found at", where)
else:
print("not found?", where)
print("ERROR" in line) Variables
- changed in this step
Printed so far
Nothing printed yetnot found? 0 True
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 6 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
line = "ERROR: disk full"setslineto'ERROR: disk full'. - Line 2.
where = line.find("ERROR")setswhereto0. The match starts at the very first character, sofind()returns 0, a position. - Line 3.
whereis false (whereis0), so the else block runs. The bug Here 0 is a position, the very start of the line, yet the test reads it as no. The text is there and the program is about to say it is not. - Line 6.
print("not found?", where)printsnot found? 0. - Line 7.
print("ERROR" in line)printsTrue. That was the last line, so the program ends. The fixinanswers the real question, yes or no, and givesTrue.
Warning
Never use the result of find() as a yes-or-no test. A match at the very start is position 0, which counts as
false, and “no match” is -1, which counts as true, so if line.find("ERROR"): gets both cases wrong: the program
above says “not found?” about a line that starts with ERROR. Write if "ERROR" in line: instead.
Checkpoint
Check: in, find() and index()
casefold() compares text without its case
The next program changes the case of four texts, a German street name among them, and compares two of them:
# lower() and casefold() both make lower case; casefold() also removes other case differences.
print("Straße".lower(), "Straße".casefold())
print("STRASSE".lower() == "Straße".lower())
print("STRASSE".casefold() == "Straße".casefold())
print("ravi KUMAR".upper(), "ravi KUMAR".title(), "ravi KUMAR".capitalize())
# title() starts a new word after every character that is not a letter, apostrophes included.
print("o'brien's cafe".title()) Output
straße strasse False True RAVI KUMAR Ravi Kumar Ravi kumar O'Brien'S Cafe
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 case.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
lower() and upper() put every letter in lower or upper case. To compare text whatever its case, use casefold()
on both sides: it removes more differences than lower(). The German street name in the program shows one of them.
lower() turns "Straße" into "straße", keeping the ß because that letter is lower case already, so the result
does not match "STRASSE".lower(), which is "strasse". casefold() writes the ß as ss, so both sides fold to
"strasse" and the comparison is True. Many languages have letters like this one, and that is why
case folding: Turning text into a form for comparing it without case, as str.casefold() does. It removes more differences than lower(): ß becomes ss, so "Straße" and "STRASSE" fold to the same text. needs casefold().
| Text | lower() |
casefold() |
|---|---|---|
"Straße" |
'straße' |
'strasse' |
"STRASSE" |
'strasse' |
'strasse' |
Only the casefold() column holds the same text twice, which is why the program’s last comparison is True.
title() starts each word with a capital and puts the rest of the word in lower case ("ravi KUMAR" becomes
"Ravi Kumar"), but to title() a word is simply a run of letters. So an apostrophe starts a new word, and
"o'brien's cafe" becomes "O'Brien'S Cafe". That suits many names and few sentences. capitalize() gives only the
first character of the whole string a capital and makes the rest lower case.
Checkpoint
Check: Comparing without case
Three digit tests accept three different sets
Three methods test for digits, and they disagree about some characters:
import unicodedata
print("text isdecimal isdigit isnumeric int(text) name")
for text in ["7", "٧", "७", "²", "½"]:
try:
number = int(text)
except ValueError:
number = "ValueError"
print(f"{text:4} {text.isdecimal()!s:9} {text.isdigit()!s:7} {text.isnumeric()!s:9} {number!s:10} {unicodedata.name(text)}") Output
text isdecimal isdigit isnumeric int(text) name 7 True True True 7 DIGIT SEVEN ٧ True True True 7 ARABIC-INDIC DIGIT SEVEN ७ True True True 7 DEVANAGARI DIGIT SEVEN ² False True True ValueError SUPERSCRIPT TWO ½ False False True ValueError VULGAR FRACTION ONE HALF
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 digits.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
isdecimal()is the strictest: it accepts only characters that can make up a base-10 number. That includes the digits of other scripts, such as the Arabic-Indic٧and the Devanagari७, andint()reads those too.isdigit()also accepts digits that cannot form a number, such as the superscript².isnumeric()accepts anything with a numeric value, even the fraction½.
The three sets sit inside each other. Every character that isdecimal() accepts passes isdigit(), and every one
that isdigit() accepts passes isnumeric(), as the figure draws with the program’s five characters:
The three digit tests, from strictest to widest
Text description of the diagram
The diagram shows three boxes, one inside the other, for the characters each test accepts.
- The innermost box is labelled isdecimal() is True. It holds the digits 7 (DIGIT SEVEN), ٧ (ARABIC-INDIC DIGIT SEVEN) and ७ (DEVANAGARI DIGIT SEVEN), with the line int() reads all three as 7.
- The middle box, around it, is labelled isdigit() is True. Besides everything in the inner box, it holds ², the superscript two: a digit that cannot make up a base-10 number.
- The outer box is labelled isnumeric() is True. Besides everything in the other two, it holds ½, the fraction one half, which has a numeric value but is not a digit.
- Every character a stricter test accepts is also accepted by the wider tests, so isdecimal() accepts the fewest characters and isnumeric() the most.
None of them accepts a minus sign, a decimal point or spaces at the ends, all of which int() or float() handle.
So to check that text is a number, try to convert it and catch the error: put int(text) in a try block and handle
ValueError, as the program does. The input and output lesson uses this to read numbers safely.
Key idea
The digit tests ask which characters a string holds, not whether it is a number: to validate a number, convert it
with int() or float() and handle the ValueError.
Checkpoint
Check: The three digit tests
translate() makes many replacements in one pass
replace() handles one substitution per call. When you need to change or delete many different characters, build a
table once with str.maketrans() and apply it with translate(), which goes through the string a single time:
# maketrans() with a third argument lists characters to delete.
phone = "(022) 2345-6789"
digits_only = str.maketrans("", "", "() -")
print(phone.translate(digits_only))
# With two strings of the same length, each character of the first
# becomes the character at the same position in the second.
devanagari_digits = str.maketrans("०१२३४५६७८९", "0123456789")
print("Flat ४०५, floor ३".translate(devanagari_digits))
# A dictionary can map a character to a longer string, or to None to delete it.
safe = str.maketrans({"&": "and", "#": None})
print("Salt & pepper #1".translate(safe)) Output
02223456789 Flat 405, floor 3 Salt and pepper 1
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 translate.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The program builds its three tables in the three ways str.maketrans() accepts:
- With three strings, the characters of the third are deleted:
str.maketrans("", "", "() -")takes the brackets, the space and the hyphen out of a phone number. - With two strings of the same length, each character of the first becomes the character at the same position in the second, so the Devanagari digits ० to ९ become 0 to 9.
- With one dictionary, a character can map to a longer string, as
&becomesand, or toNone, which deletes it.
A character that the table does not name stays as it is. Because the table is built once, one translate() call per
line cleans a whole file, where a chain of replace() calls would read each line again for every character it
changes.
Checkpoint
Check: Tables with maketrans()
Practise: tidy up a typed name
Names typed into forms arrive with stray spaces and capitals in odd places. Write the function that tidies one up:
it needs split() and join() for the spaces, title() for the capitals, and a lower-case comparison for small
words such as “van” and “de”. Run the sample tests in the page as often as you like; the first hint is one click
away if you get stuck:
Exercise · Easy · Python
Tidy up a name that someone typed
Names typed into a form arrive with extra spaces, tabs and capitals in odd places. Write normalise_name(raw), which returns the name tidied up by these rules:
- No spaces, tabs or line breaks at either end, and exactly one space between words.
- Each word written with
str.title(), so"aNNE-marie"becomes"Anne-Marie"and"o'neil"becomes"O'Neil". - The particles listed in
PARTICLES(da, de, del, der, di, la, le, van and von) in lower case however they were typed, except when one is the first word:"ludwig VAN beethoven"becomes"Ludwig van Beethoven", but"van gogh"becomes"Van Gogh". - A name with no words at all, such as
""or" ", gives"".
Names in scripts without capital letters, such as "राम कुमार", only have their spaces tidied: title() leaves their letters as they are. The sample tests import your function from names.py.
Starter code · names.py
PARTICLES = ("da", "de", "del", "der", "di", "la", "le", "van", "von")
def normalise_name(raw):
"""Return raw as a tidy name: single spaces, each word capitalised, particles such as 'van' in lower case."""
# Replace this line with your code.
return raw The sample tests · test_names.py
from names import normalise_name
def test_spaces():
"""removes spaces at the ends and keeps one space between words"""
assert normalise_name(" ada lovelace ") == "Ada Lovelace"
assert normalise_name("grace\thopper\n") == "Grace Hopper"
def test_capitals():
"""writes each word with a capital letter first and the rest in lower case"""
assert normalise_name("aLAN tURING") == "Alan Turing"
assert normalise_name("anne-marie o'neil") == "Anne-Marie O'Neil"
def test_particles():
"""keeps particles after the first word in lower case"""
assert normalise_name("ludwig VAN beethoven") == "Ludwig van Beethoven"
assert normalise_name("maría DEL carmen") == "María del Carmen"
assert normalise_name("Vincent van Gogh") == "Vincent van Gogh"
def test_first_word():
"""capitalises a particle that is the first word"""
assert normalise_name("van gogh") == "Van Gogh"
assert normalise_name("de la cruz") == "De la Cruz"
def test_other_scripts():
"""tidies the spaces of names in other scripts"""
assert normalise_name(" राम कुमार ") == "राम कुमार"
assert normalise_name("ÉMILE zola") == "Émile Zola"
def test_blank():
"""gives an empty string for a name with no words"""
assert normalise_name("") == ""
assert normalise_name(" \t ") == "" A hint
raw.split() with no argument already deals with the spaces: it drops them at both ends and treats any run of spaces, tabs and line breaks as one separator, so " ".join(raw.split()) puts single spaces back. Then go through the words one at a time and decide for each: is it the first word, and is word.casefold() one of PARTICLES?
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Then work through the lesson’s questions. They begin with the idea you seem least sure of, step up a level after each right answer, and give the reason for every answer as soon as you choose it:
Practice that adapts to you
Practise this lesson
17 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · What is the difference between find() and index() on a string?
Both search a string for a substring and return the position where the first match starts, so
"disk full".find("full") and "disk full".index("full") are both 5. They differ when there is no match: find()
returns -1, while index() raises ValueError. Use index() when a missing match means the data is wrong, so the
program stops at the cause instead of carrying a -1 forward, and find() when a missing match is normal and you test
for it. Neither result works as a yes-or-no test, because a match at the very start is 0, which is false, while -1 is
true. To ask whether one string contains another, write "full" in text. Both take optional start and end
positions, and rfind() and rindex() search from the right.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A sign-up form stores email addresses exactly as typed. Months later one person has two accounts, one for " Asha.Rao@Example.com" and one for "asha.rao@example.com". Explain how that happened, how you would compare addresses from now on, and what you would do about the accounts that already exist.
-
Fresher to mid
An import script reads a CSV export with fields = line.strip().split(","). It works until a customer's address, saved in quotes as "Flat 4, MG Road", shifts every later column by one. Explain the bug, fix it, and say how you would test the import.
Key takeaways
- String methods return new strings, so assign the result; chaining (
raw.strip().casefold()) applies them in order. strip()cleans the ends;split(",")keeps empty fields whilesplit()splits on runs of whitespace;join()glues string pieces with a separator.strip(".com")removes any of those characters;removeprefix()andremovesuffix()remove an exact text once.- Test containment with
in.find()returns -1 for no match and 0 for a match at the start, so it is not a yes-or-no test;index()raisesValueErrorinstead. - Compare text without case with
casefold()on both sides, and translate many characters at once withstr.maketrans()andtranslate(). isdecimal(),isdigit()andisnumeric()accept different characters; to validate a number, convert it withint()and catchValueError.
Terms in this lesson
- case folding
- Turning text into a form for comparing it without case, as str.casefold() does. It removes more differences than lower(): ß becomes ss, so "Straße" and "STRASSE" fold to the same text.
- method
- A function that belongs to a value and is called with a dot after it, such as text.strip(). String methods return a new string and leave the original as it was.
- whitespace
- Characters that show as empty space, such as spaces, tabs and line breaks. strip() removes them from both ends, and split() with no argument splits on any run of them.
References
- String Methods (The Python Standard Library) (Python Software Foundation)
- str.casefold() (The Python Standard Library) (Python Software Foundation)
- str.removeprefix() and str.removesuffix() (The Python Standard Library) (Python Software Foundation)
- PEP 616: String methods to remove prefixes and suffixes (Python Software Foundation)
- int() (Built-in Functions) (Python Software Foundation)
- str.maketrans() and str.translate() (The Python Standard Library) (Python Software Foundation)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress