Strings: f-strings, slicing and methods
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 rightNone 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.
Your task
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.
- clean is EDI-1430-GLA (not done yet)
- origin is EDI, sliced from clean (not done yet)
- time is 14:30, from slices of clean (not done yet)
- Print the sentence with an f-string (not done yet)
The checklist ticks itself off as you work in the editor: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
s[0]- The character at a position, counting from 0; s[-1] is the last one Python docs →
s[2:5]- A slice: positions 2, 3 and 4 (the end is not included) Python docs →
.strip()- A copy of the string without the spaces (and new lines) at both ends Python docs →
.upper()- A copy of the string in capitals (.lower() for small letters) Python docs →
f"{x}"- An f-string: the values in braces are worked out and put in the text; {x:.2f} shows 2 decimal places Python docs →
len()- How many items (characters, list items, dict keys) something has Python docs →