Fundamentals · Lesson 7 of 94

String methods and f-strings

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

A method is a function that belongs to a value. You call it with a dot: name.upper() asks the string in name to give you an uppercase copy. Strings come with dozens of methods built in, and because strings are immutable, every one of them returns a new string and leaves the original alone.

The methods split into three families, and knowing the families is more useful than memorizing the list.

Family Methods Question they answer
Change upper, lower, title, strip, replace Give me a cleaned-up copy
Inspect startswith, endswith, isdigit, find Is this text shaped the way I think?
Split/join split, join, splitlines Turn text into pieces, or pieces into text

The one you will use most is strip(), because text from users and files arrives with stray spaces and newlines at the ends. split() breaks a sentence into a list of words, and " ".join(words) puts a list back together with a chosen separator. Notice that join is called on the separator, not the list; it reads oddly for about a week and then becomes muscle memory.

String methods and f-strings: '  Hello World  ' → 'Hello World' → 'hello world' → ['hello', 'world' → 'hello-world'
String methods and f-strings · Figure 1 · Open for full size

An f-string is how you put values into text. Write f before the opening quote, then anything inside curly braces is evaluated and inserted. You caught a glimpse of one in the preview program back in the welcome lesson. The power is in the format spec after a colon: {price:.2f} gives two decimals, {name:>10} right-aligns in ten characters, {count:,} adds thousands separators. Since Python 3.12 you can even reuse the same quote character inside the braces.

String methods and f-strings: total: the value → >8: right-align, width 8 → .2f: 2 decimals, fixed
String methods and f-strings · Figure 2 · Open for full size

You will meet two older styles in existing code. "Hello %s" % name is the C-era form, and "Hello {}".format(name) came next. Both still work and both are worth recognizing, but write f-strings in new code: they are shorter, faster, and the values sit exactly where they appear in the output. Python 3.14 also adds t-strings, a template form for libraries that need to process the pieces before joining them; you will not need them in this course.

Code

Start with the cleaning family. Each call returns a new string; the original stays as it was, which the last line proves.

# clean.py
raw = "   Mahmudul Islam \n"

print(repr(raw))
print(repr(raw.strip()))
print(raw.strip().upper())
print(raw.strip().lower().replace(" ", "_"))
print(repr(raw))
Output
'   Mahmudul Islam \n'
'Mahmudul Islam'
MAHMUDUL ISLAM
mahmudul_islam
'   Mahmudul Islam \n'

Now inspecting and searching. in answers yes or no, find tells you where, and returns -1 when the text is not there instead of raising an error.

# search.py
email = "mahmud@hexcursion.com"

print("@" in email)
print(email.find("@"))
print(email.find("z"))
print(email.startswith("mahmud"))
print(email.endswith(".org"))
print("2026".isdigit())
Output
True
6
-1
True
False
True

Splitting and joining turn text into a list and back. The separator you join with can be anything, including an empty string.

# split_join.py
sentence = "learn python one idea at a time"
words = sentence.split()

print(words)
print(len(words))
print("-".join(words))
print("".join(w[0] for w in words).upper())
Output
['learn', 'python', 'one', 'idea', 'at', 'a', 'time']
7
learn-python-one-idea-at-a-time
LPOIAAT

Format specs make f-strings line up. This receipt aligns names to the left and prices to the right with two decimals, which is exactly what plain concatenation cannot do.

# receipt.py
items = [("coffee", 3.5), ("bagel", 2.25), ("orange juice", 4)]
total = sum(price for _, price in items)

for name, price in items:
    print(f"{name:<14}{price:>8.2f}")
print(f"{'total':<14}{total:>8.2f}")
print(f"items: {len(items)}, big number: {1234567:,}")
Output
coffee            3.50
bagel             2.25
orange juice      4.00
total             9.75
items: 3, big number: 1,234,567

Try it yourself

Create namecard.py. Ask for nothing yet; store a full name with messy spacing like " ada lovelace ". Print it cleaned and in title case, print the initials, and print an f-string line with the name left-aligned in 20 characters followed by the number of letters right-aligned in 4. Check the alignment with a ruler of dashes above it.

Common mistakes

What's next

You can shape text however you need. Next you will get text from the person running your program, with input(), and turn it into the type your code expects.

Course overview