String Methods & Formatting
Beginner · 18 min read · ▶ live playground · ✦ checkpoint
Text cleanup looks boring until a player types " mina " and your scoreboard prints it exactly that way. Python strings come with tools for cleanup, searching, and polished output, so you can turn rough text into text meant for humans.
Methods are tools on strings
A method is behavior attached to an object, called with a dot and parentheses. Think of a method like a tool clipped onto a value: the string is the thing, and .upper() is one tool you can use on it.
String methods do not change the old string in place. That fits the immutability rule from lesson 3.2. They return a string result; when the text changes, that result is a new string object.
raw_player = " Mina Rao "
cheer = "Go Mina, go Mina!"
clean_player = raw_player.strip()
print("[" + raw_player + "]")
print("[" + clean_player + "]")
print(clean_player.upper())
print(clean_player.lower())
print(cheer.replace("Mina", "Ravi"))[ Mina Rao ][Mina Rao]MINA RAOmina raoGo Ravi, go Ravi!
strip() removes whitespace from the start and end. Whitespace means spacing characters such as spaces, tabs, and newlines.
upper() creates an uppercase version. lower() creates a lowercase version. replace() creates a copy where one piece of text is swapped for another.
Notice the first output line: raw_player still has its spaces. strip() did not scrub the old object. It built a cleaned string and the name clean_player now refers to that new object.
Read method calls left to right: value, dot, method name, parentheses. The text inside the parentheses gives the method what it needs. replace("Mina", "Ravi") means "make a copy where this old text becomes this new text."
Split and join move between pieces
split() breaks one string into pieces. It returns a list, an ordered collection of values; collections get their full story in Section 5, so for now read the square brackets as "Python is showing several pieces."
join() does the reverse: it takes several string pieces and glues them together with a separator string between them.
tag_line = "python, strings, practice"
tags = tag_line.split(", ")
joined_tags = " | ".join(tags)
tidy_name = " ".join(" Mina Rao ".split())
print(tags)
print(joined_tags)
print(tidy_name)['python', 'strings', 'practice']python | strings | practiceMina Rao
The separator matters. In tag_line.split(", "), Python cuts at comma-space. In " | ".join(tags), Python puts space-pipe-space between the pieces.
The tidy_name line uses split() with nothing inside the parentheses. That means "split on whitespace." Then " ".join(...) puts the pieces back together with one clean space. You don't need to master lists yet to use this pattern carefully.
This pair is common because real text often arrives as one messy line and needs to leave as a neat sentence. split() gives you pieces. join() chooses how those pieces should be shown together.
Try it - clean a name tag
Run this, then change the spacing, casing, and city name. Predict each line before you run.
Search and test text
A membership test asks whether one value is inside another value. For strings, "needle" in text returns a Boolean: True if the text is found, False if it is not.
find() searches for text and returns the index where it starts. If it cannot find the text, it returns -1.
startswith() tests the beginning. endswith() tests the end. These are useful when the position matters more than "anywhere inside."
message = "Mina scored 42 points"
print("scored" in message)
print("Ravi" in message)
print(message.find("42"))
print(message.find("gold"))
print(message.startswith("Mina"))
print(message.endswith("points"))TrueFalse12-1TrueTrue
Use in when you only need yes or no. Use find() when the starting index matters. The -1 result is a real signal: Python looked and did not find the text.
These tests start to shine in Section 4, when your program can choose different paths. For now, you are learning the questions strings can answer.
Searches are case-sensitive. "mina" in message is False when the message starts with "Mina". If you want a case-insensitive check later, the usual move is to make both pieces the same case first, then test.
F-strings can format values
An f-string expression is code inside {} in an f-string; Python runs it and inserts the result. You used simple name insertion in lesson 2.4. The braces can also hold arithmetic.
A format spec is a formatting instruction after : inside an f-string expression. It tells Python how the value should look.
player = "Mina"
score = 42
bonus = 8
ticket_price = 7.5
team_total = 12345.678
print(f"{player} scored {score + bonus} points")
print(f"Ticket price: ${ticket_price:.2f}")
print(f"Team total: {team_total:,.2f}")
print("{} scored {} points".format(player, score))
print("Ticket price: $%.2f" % ticket_price)Mina scored 50 pointsTicket price: $7.50Team total: 12,345.68Mina scored 42 pointsTicket price: $7.50
In {ticket_price:.2f}, .2f means "show two digits after the decimal point." In {team_total:,.2f}, the comma adds thousands separators and .2f keeps two decimal places.
Legacy formatting is older string formatting style you will still see in existing Python code. "{}".format(...) and "%.2f" % value both work, but f-strings are the everyday choice for new code because they keep the value close to the sentence.
Formatting changes the displayed text, not the original value. ticket_price is still the float 7.5; the f-string creates a string that shows $7.50. That distinction keeps the puzzle-piece idea from lesson 2.2 intact: numbers remain useful for arithmetic, and formatted strings become useful for output.
Build clean multiline output
Clean output often needs more than one line. Triple-quoted strings from lesson 3.1 pair nicely with f-strings because the line breaks in the code become line breaks in the output.
player = "Mina"
mood = "focused"
score = 42
report = f"""Player: {player}
Mood: {mood}
Score: {score}
Next target: {score + 10}"""
print(report)Player: MinaMood: focusedScore: 42Next target: 52
This is easier to read than a long chain of + pieces with \n sprinkled through it. Use concatenation for small joins. Use multiline f-strings when you are shaping a small block of output for a person.
Checkpoint
Answer all three to mark this lesson complete
You now have the everyday string tools: clean, search, split, join, and format. Section 4 gives those Boolean answers somewhere to go, so your programs can stop only printing facts and start making choices.