Python Functions and Methods: A Topic-by-Topic Reference · Lesson 3 of 12

Lesson 3: String Methods, Part 1: Changing and Cleaning Text

upper, lower, title, capitalize, strip, replace, center, zfill, format and f-strings, with examples.

Lesson 3: String Methods, Part 1: Changing and Cleaning Text

A method is a function that belongs to a value, called with a dot: text.upper(). Strings cannot be changed in place, so every method returns a new string.

Changing case

upper(), lower()

All capitals or all small letters.

name = "Kathmandu Valley"
print(name.upper())
print(name.lower())

Output:

KATHMANDU VALLEY
kathmandu valley

title(), capitalize(), swapcase()

title capitalises every word, capitalize only the first letter, swapcase flips each letter.

s = "hELLO wORLD"
print(s.title())
print(s.capitalize())
print("Hello World".swapcase())

Output:

Hello World
Hello world
hELLO wORLD

casefold()

A stronger lower() for comparing text in many languages.

print("Straße".lower())
print("Straße".casefold())
print("HELLO".casefold() == "hello")

Output:

straße
strasse
True

Removing and replacing

strip(), lstrip(), rstrip()

Remove spaces (or listed characters) from both ends, the left or the right.

print("[" + "   hi   ".strip() + "]")
print("[" + "   hi   ".lstrip() + "]")
print("[" + "   hi   ".rstrip() + "]")
print("***wow***".strip("*"))

Output:

[hi]
[hi   ]
[   hi]
wow

replace(old, new, count)

Replaces every occurrence (or the first count).

print("a-b-c".replace("-", "+"))
print("a-b-c".replace("-", "+", 1))
print("hello".replace("l", ""))

Output:

a+b+c
a+b-c
heo

removeprefix(p), removesuffix(s)

Remove text from the start or end, only if it is there. (Python 3.9+)

print("report.pdf".removesuffix(".pdf"))
print("https://merosir.com".removeprefix("https://"))

Output:

report
merosir.com

translate() with str.maketrans()

Replace many single characters at once, or delete some.

table = str.maketrans("aeiou", "12345")
print("education".translate(table))
print("a1b2c3".translate(str.maketrans("", "", "0123456789")))

Output:

2d5c1t34n
abc

Spacing and alignment

center(w), ljust(w), rjust(w)

Pad a string to a width. Add a fill character as the second argument.

print("[" + "Nepal".center(11, "-") + "]")
print("[" + "Nepal".ljust(9) + "]")
print("[" + "Nepal".rjust(9) + "]")

Output:

[---Nepal---]
[Nepal    ]
[    Nepal]

zfill(w)

Pad a number-like string with zeros on the left.

print("42".zfill(5))
print("7".zfill(3))
print("-5".zfill(4))

Output:

00042
007
-005

expandtabs()

Turn tab characters into spaces.

print("a\tb".expandtabs(4))

Output:

a   b

Building text from values

f-strings

Put values and expressions inside { }. After a colon you can format: width, decimals, thousands separators, percentages.

price = 1234567.891
name = "Sita"
print(f"{name} paid Rs {price:,.2f}")
print(f"{0.256:.1%}")
print(f"{name:>8}|{name:<8}|{name:^8}|")
print(f"{255:b} {255:x} {7:03d}")

Output:

Sita paid Rs 1,234,567.89
25.6%
    Sita|Sita    |  Sita  |
11111111 ff 007

format() and %

Older ways that you will see in existing code. They do the same job.

print("{} scored {}".format("Ram", 85))
print("{1} {0}".format("world", "hello"))
print("%s is %d years old" % ("Gita", 17))

Output:

Ram scored 85
hello world
Gita is 17 years old

str.join(iterable)

Joins a list of strings using the string it is called on as the glue. Much faster than adding in a loop.

print(", ".join(["red", "green", "blue"]))
print("".join(["a", "b", "c"]))
print("-".join(str(n) for n in range(1, 5)))

Output:

red, green, blue
abc
1-2-3-4

* and +

Repeat with * and join with +.

print("ab" * 3)
print("=" * 20)
print("Mero" + "Sir")

Output:

ababab
====================
MeroSir

Never build a long string by adding in a loop (s += "x") when you can collect pieces in a list and join once.

Try it yourself

  1. Clean " RAM shrestha " into "Ram Shrestha".
  2. Print a receipt line with the item left-aligned and the price right-aligned in 20 characters.
  3. Turn the list ["2026", "10", "04"] into "2026-10-04".

Next lesson: text, part two (searching and splitting).

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 3: String Methods, Part 1: Changing and Cleaning Text | MeroSir