Skip to content

Strings: f-strings, slicing and methods

BeginnerLesson 3 of 147 min

Work with text in Python: pick out characters by position, cut pieces out with slices, tidy text with string methods and build sentences with f-strings.

A string is a sequence of characters, and each one has a position, counting from 0:

 c   a   n   a   l
 0   1   2   3   4
-5  -4  -3  -2  -1
word = "canal"
print(word[0], word[4], word[-1])  # c l l
print(len(word))                   # 5

Negative positions count from the end, so word[-1] is always the last character, however long the string is.

Slices

word[start:stop] cuts out a piece: from start up to, but not including, stop. Leave one out to go from the beginning or to the end:

word = "canal"
print(word[1:4])  # ana
print(word[:2])   # ca
print(word[2:])   # nal

The "not including" rule makes the sums tidy: word[:2] + word[2:] is the whole word again, and word[1:4] is 4 - 1 = 3 characters long.

Methods

Strings come with methods, functions you call with a dot:

name = "  Ada Lovelace "
print(name.strip())          # "Ada Lovelace": spaces gone from both ends
print(name.upper())          # "  ADA LOVELACE "
print(name.replace("a", "4"))
print(name.strip().lower())  # methods chain, left to right

None of these change name. Strings can never be changed once made (they're immutable); a method hands you a new string, and you keep it by giving it a name: name = name.strip().

f-strings

Put an f before the opening quote, and anything in {braces} is worked out and dropped in:

item = "lamp"
price = 18.5
print(f"The {item} costs £{price:.2f}")  # The lamp costs £18.50
print(f"{item.upper()} x2 = {price * 2}")

After a colon you can say how to format the value: :.2f means two decimal places.

Careful:Forget the f and the braces print as they are: "The {item} costs".

More in the Python docs: string methods, slicing and f-strings.

Your turn

ticket is a messy train ticket code. Make clean the code with the spaces stripped and in capitals (EDI-1430-GLA). Make origin its first three letters and time the text 14:30, both cut from clean with slices. Then print Train EDI leaves at 14:30 with an f-string.

Next →