Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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().

  • Beginner
  • 15 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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:

Cleaning a messy line Python · clean_line.py
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

  • 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() and rstrip() do only the left or the right end. A line read from a file usually ends with \n, so line.rstrip("\n") or line.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]) raises TypeError, so convert numbers with str() 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():

Interactive · line by line Splitting a typed line and keeping the fields that hold a name Step through the program. The cells under fields are the pieces split() made; the flag marks the field the loop reads next.

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

After line 8: raw is ' Mango, apple ,,kiwi \n'; fields is ['Mango', ' apple ', '', 'kiwi']; names is ['Mango', 'apple', 'kiwi']; field is 'kiwi'; name is 'kiwi'.raw' Mango, apple ,,kiwi \n'fields'Mango'0' apple '1''2'kiwi'3names'Mango'0'apple'1'kiwi'2field'kiwi'name'kiwi'
  • just taken by the loop
  • changed in this step
  • passed by the loop
  • read next
  • where the loop stopped

Printed so far

Mango | 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.

Line run 8
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. raw = " Mango, apple ,,kiwi \n" sets raw to ' Mango, apple ,,kiwi \n'.
  3. Line 2. fields = raw.strip().split(",") sets fields to ['Mango', ' apple ', '', 'kiwi']. strip() took the space and the line break off the ends first. Then split(",") cut at every comma, so the two commas in a row left an empty field at position 2.
  4. Line 3. names = [] makes names a list of 0 items.
  5. Line 4. for field in fields: takes the item at position 0 of fields: field is 'Mango'.
  6. Line 5. name = field.strip() sets name to 'Mango'.
  7. Line 6. name is true (name is 'Mango'), so the block under if name: runs.
  8. Line 7. names.append(name) adds 'Mango' to the end of names.
  9. Line 4. for field in fields: takes the item at position 1 of fields: field is ' apple '.
  10. Line 5. name = field.strip() sets name to 'apple' (it was 'Mango').
  11. Line 6. name is true (name is 'apple'), so the block under if name: runs.
  12. Line 7. names.append(name) adds 'apple' to the end of names.
  13. Line 4. for field in fields: takes the item at position 2 of fields: field is ''.
  14. Line 5. name = field.strip() sets name to '' (it was 'apple').
  15. Line 6. name is false (name is ''), so Python skips the block under if name:. Key point This is why the loop needs its if: split(",") keeps the empty field, and only the test keeps it out of names.
  16. Line 4. for field in fields: takes the item at position 3 of fields: field is 'kiwi'.
  17. Line 5. name = field.strip() sets name to 'kiwi' (it was '').
  18. Line 6. name is true (name is 'kiwi'), so the block under if name: runs.
  19. Line 7. names.append(name) adds 'kiwi' to the end of names.
  20. Line 4. for field in fields: finds no item at position 4 of fields (it has 4 items), so the loop ends.
  21. Line 8. print(" | ".join(names)) prints Mango | 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()

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print("a,,b".split(","))
    Show the answer: Question 1 of 2

    Answer: ['a', '', 'b']

    With a separator, split() returns one piece more than there are separators, empty pieces included. That keeps the positions of the fields, as a spreadsheet row needs.

  2. Question 2 of 2 Which call gives "1, 2, 3"?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: ", ".join(["1", "2", "3"])

    separator.join(pieces) turns a list of strings into one string. It is the opposite of split(), and the pieces must already be strings.

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:

strip() or removesuffix()? Python · strip_or_removesuffix.py
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

"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

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(repr("level".strip("lev")))
    Show the answer: Question 1 of 2

    Answer: ''

    The argument of strip() is a set of characters. It removes any of them from each end until it reaches one that is not in the set, here never, so the result is the empty string.

  2. Question 2 of 2 host is "www.wonders.example". Which call gives "wonders.example"?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: host.removeprefix("www.")

    To remove an exact beginning, use removeprefix(). lstrip() and strip() remove characters from a set, and keep going for as long as the next character is in it.

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:

Searching a log line Python · search.py
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

  • "disk" in line is the clearest way to ask whether one string contains another. Like every comparison of strings it is case-sensitive, so "DISK" in line is False.
  • 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 raises ValueError when there is no match, as the last line of the program shows. Use it when a missing match means something is wrong.
  • startswith() and endswith() 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:

Interactive · line by line A match at position 0 that an if reads as false Step through the program and watch the value of where, then which branch the if takes.

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

After line 7: line is 'ERROR: disk full'; where is 0.line'ERROR: disk full'where0
  • changed in this step

Printed so far

not 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.

Line run 7
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. line = "ERROR: disk full" sets line to 'ERROR: disk full'.
  3. Line 2. where = line.find("ERROR") sets where to 0. The match starts at the very first character, so find() returns 0, a position.
  4. Line 3. where is false (where is 0), 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.
  5. Line 6. print("not found?", where) prints not found? 0.
  6. Line 7. print("ERROR" in line) prints True. That was the last line, so the program ends. The fix in answers the real question, yes or no, and gives True.

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()

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print("chai".find("x"), "chai".find("c"))
    Show the answer: Question 1 of 2

    Answer: -1 0

    find() gives the position where the first match starts, or -1 when there is none. A match at the very start is 0, which is why the result is not a yes-or-no test.

  2. Question 2 of 2 Which test is true exactly when line starts with "ERROR"?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: line.startswith("ERROR")

    startswith() is the test for a beginning, as endswith() is for an ending. find() returns positions, and in asks about the whole string.

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:

Changing case Python · case.py
# 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

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.

Case Converter Paste a sentence to compare upper, lower, title and other case styles side by side.

Checkpoint

Check: Comparing without case

  1. Question 1 of 2 Which comparison is True?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: "Straße".casefold() == "STRASSE".casefold()

    casefold() removes more case differences than lower(), which is what a comparison that ignores case needs. Fold both sides, or the comparison fails whenever the stored text has other capitals.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    print("it's d'souza".title())
    Show the answer: Question 2 of 2

    Answer: It'S D'Souza

    title() starts every run of letters with a capital, so an apostrophe inside a word splits it. It suits many names, and few sentences.

Three digit tests accept three different sets

Three methods test for digits, and they disagree about some characters:

isdecimal(), isdigit() and isnumeric() Python · digits.py
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

  • 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 ७, and int() 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:

Three nested boxes: isdecimal() inside isdigit() inside isnumeric(). 7, ٧ and ७ pass all three, ² the outer two, ½ only the outer.isnumeric() is Trueisdigit() is Trueisdecimal() is True7٧७int() reads all three as 7² superscript two½ fraction one half

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

  1. Question 1 of 2 Which of these tests is False for the superscript two, "²"?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: "²".isdecimal()

    The three tests accept nested sets: decimal characters, then digits, then anything with a numeric value. The superscript two is a digit but not a decimal character, so int("²") raises ValueError.

  2. Question 2 of 2 A form field must hold a whole number, which may be negative, such as "-12". Which check works?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Call int(text) in a try block and handle ValueError

    The digit tests describe characters. To find out whether text is a number, convert it with int() (or float()) and handle the error.

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:

Character tables with maketrans() Python · translate.py
# 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

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 & becomes and, or to None, 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.

Whitespace Remover Trim the lines of pasted text and collapse runs of spaces and tabs, the way strip() and split() tidy text in code.

Checkpoint

Check: Tables with maketrans()

  1. One question What does this print?

    Read the code, then choose one answer.

    table = str.maketrans("", "", "-")
    print("98-765-43210".translate(table))
    Show the answer: One question

    Answer: 9876543210

    With three arguments, str.maketrans() maps the characters of the first string to those of the second and deletes those of the third. translate() then goes through the text once.

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?

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.

  1. Question 1 of 17 What does strip_or_removesuffix.py print?

    What does this program print? Choose one answer.

    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"))
    Show the answer: Question 1 of 17

    Answer: it prints

    ha
    mocha
    i comic
    notes.txt

    strip(".com") treats its argument as a set of characters and removes any of ., c, o and m from both ends, so it eats into the words themselves. removesuffix(".com") removes that exact ending once, and leaves the string unchanged when it does not end that way, which is why notes.txt keeps its .txt.

  2. Question 2 of 17 What does this print?

    Read the code, then choose one answer.

    print("  red,  green  ".split())
    Show the answer: Question 2 of 17

    Answer: ['red,', 'green']

    With no argument, split() splits on runs of whitespace and drops the empty pieces at the ends. It does not know about commas, so the comma stays attached to red. split(",") would split on the comma instead and keep the spaces.

  3. Question 3 of 17 Which test is true exactly when the text "error" appears somewhere in line?

    Choose one answer.

    Show the answer: Question 3 of 17

    Answer: "error" in line

    in gives True or False directly. find() returns -1, which is true, when there is no match and 0, which is false, for a match at the start, so line.find("error") is wrong both ways, and > 0 still misses a match at position 0. index() raises ValueError instead of returning a false value.

  4. Question 4 of 17 A user types a city name and you want to compare it with a stored one, ignoring case. Which is the most reliable?

    Choose one answer.

    Show the answer: Question 4 of 17

    Answer: typed.casefold() == stored.casefold()

    casefold() is meant for caseless comparison: it removes more case differences than lower(), for example it turns ß into ss, so "STRASSE" and "Straße" match. Both sides must be folded; comparing a changed copy of one side with the unchanged other side fails whenever the stored text has different capitals.

  5. Question 5 of 17 text is the superscript two, "²". Which of these are true?

    Choose every answer that is right.

    Show the answer: Question 5 of 17

    Answer:

    • text.isnumeric() is True
    • text.isdigit() is True

    A superscript digit counts as a digit and as numeric, but it is not a decimal character, the kind that can make up a base-10 number, so isdecimal() is False and int("²") raises ValueError. To check that text is a whole number, try int() and catch the ValueError.

  6. Question 6 of 17 What does strip() with no argument remove?

    Choose one answer.

    Show the answer: Question 6 of 17

    Answer: Whitespace at both ends, such as spaces, tabs and line breaks

    strip() removes whitespace from both ends; lstrip() and rstrip() clean one end. Spaces inside the text are left alone.

  7. Question 7 of 17 What does this print?

    Read the code, then choose one answer.

    print(" ".join("  a   b\tc ".split()))
    Show the answer: Question 7 of 17

    Answer: a b c

    " ".join(text.split()) is a common idiom: it collapses every run of spaces, tabs and line breaks into one space and trims both ends.

  8. Question 8 of 17 What does this print?

    Read the code, then choose one answer.

    print("file.txt.txt".removesuffix(".txt"))
    Show the answer: Question 8 of 17

    Answer: file.txt

    removeprefix() and removesuffix() remove their exact text once, or return the string unchanged.

  9. Question 9 of 17 A program must drop .csv from file names such as "sales.csv". Which line is right for every such name?

    Choose one answer.

    Show the answer: Question 9 of 17

    Answer: name.removesuffix(".csv")

    A file extension is an exact ending, which is what removesuffix() removes. The strip methods work on sets of characters and damage names that end in one of those letters.

  10. Question 10 of 17 What does index() do when the text it looks for is not there?

    Choose one answer.

    Show the answer: Question 10 of 17

    Answer: It raises ValueError

    index() and find() both give the position of the first match. With no match, find() returns -1 and index() raises ValueError, which suits code where a missing match means something is wrong.

  11. Question 11 of 17 What does this print?

    Read the code, then choose one answer.

    print("aaaa".count("aa"))
    Show the answer: Question 11 of 17

    Answer: 2

    After each match count() carries on from the end of it, so matches never overlap: "aaaa" holds "aa" twice.

  12. Question 12 of 17 Which method is meant for comparing text without its case?

    Choose one answer.

    Show the answer: Question 12 of 17

    Answer: casefold()

    Fold both sides with casefold() before comparing. lower() is fine for display, and for comparing only text known to be plain English.

  13. Question 13 of 17 A login compares names with typed.lower() == stored.lower(). A user typing "STRASSE" cannot match the stored "Straße". What is the right fix?

    Choose one answer.

    Show the answer: Question 13 of 17

    Answer: Compare typed.casefold() with stored.casefold()

    The code already folds both sides, but with the weaker method. casefold() is the one the documentation names for caseless matching.

  14. Question 14 of 17 Which characters does isdecimal() accept?

    Choose one answer.

    Show the answer: Question 14 of 17

    Answer: Characters that can make up a base-10 number, in any script

    isdecimal() is the strictest digit test: characters that can form a base-10 number, from any script, and nothing else.

  15. Question 15 of 17 The text below uses the Arabic-Indic digits for 4 and 2. What does this print?

    Read the code, then choose one answer.

    print(int("٤٢") + 1)
    Show the answer: Question 15 of 17

    Answer: 43

    int() accepts every character that isdecimal() accepts, whatever its script, and gives an ordinary int.

  16. Question 16 of 17 In str.maketrans("ab", "xy", "c"), what happens to c when the table is used?

    Choose one answer.

    Show the answer: Question 16 of 17

    Answer: It is deleted

    str.maketrans(from, to, delete) maps each character of from to the one at the same position in to, and deletes the characters of delete.

  17. Question 17 of 17 A cleaner must turn the ten Devanagari digits into 0 to 9 in every line of a large file. Which is the better plan?

    Choose one answer.

    Show the answer: Question 17 of 17

    Answer: Build one table with str.maketrans() and call translate() on each line

    translate() is the tool for many one-character changes at once: one table, one pass per line.

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.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

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 while split() splits on runs of whitespace; join() glues string pieces with a separator.
  • strip(".com") removes any of those characters; removeprefix() and removesuffix() 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() raises ValueError instead.
  • Compare text without case with casefold() on both sides, and translate many characters at once with str.maketrans() and translate().
  • isdecimal(), isdigit() and isnumeric() accept different characters; to validate a number, convert it with int() and catch ValueError.

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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.