Python strings, slicing and f-strings
Builds on lessons 1 to 3. Start at lesson 1
Learn
Indexes and slices
A string is a sequence of characters, and each character has a position called an index. Python counts from 0, not 1.
word = "python"
# 012345
word[0] # 'p'
word[5] # 'n'
word[-1] # 'n' negative indexes count from the endlen(word) gives the length, 6. Asking for word[6] is an IndexError: the last index is always len - 1.
A slice grabs a chunk: word[start:stop]. It includes start but stops before stop. So word[0:2] is "py". Leave a side empty to mean "from the beginning" or "to the end": word[2:] is "thon", word[:-1] is "pytho".
Learn
String methods and f-strings
Strings come with methods, functions you call with a dot:
s.upper()ands.lower()change case.s.strip()removes spaces from both ends.s.replace("a", "b")swaps text.s.count("o")counts how many times something appears.
Here is the catch: strings are immutable. Methods never change the original; they give you back a new string. name.upper() on its own line does nothing useful. You need name = name.upper() to keep the result.
To build text from variables, use an f-string: put f before the quote and drop variables into { }.
age = 15
print("I am " + str(age) + " and next year I'll be " + str(age + 1))age ← 15
OUTPUT "I am " + INT_TO_STRING(age) + " and next year I'll be " + INT_TO_STRING(age + 1)age = 15
print(f"I am {age} and next year I'll be {age + 1}")You can put any expression inside the braces, and {price:.2f} shows a number with exactly 2 decimal places. Way nicer than gluing strings with +, which also refuses to mix strings and numbers.
GCSE exam boards
- OCR 2.2.3 Strings, files, arrays, sub programs, SQL
- AQA 3.2.8 Strings
- Edexcel 6.3.3 Strings
Try
Run it: slicing a word
The example is already in the editor. Run it, change one thing, and run it again.
word = "python"
print(word[0], word[-1]) # first and last letters
print(word[0:2], word[2:]) # slices
print(len(word))
shout = word.upper() # word itself is unchanged
print(word, shout)
name = " pixelpanda "
print("[" + name.strip() + "]")
price = 4.5
print(f"{word} costs {price:.2f} and has {len(word)} letters")
Practice
Print the initials
Using indexing on first and last, print the initials of the name, with a dot after each, so the output is exactly A.L. Use an f-string.
Constraint
- Work it out with code. Printing the answer as text doesn't count.
first = "Ada"
last = "Lovelace"
print(f"{first}.{last}.")
Practice
Tidy username
raw is a messy username. Strip the spaces off both ends and make it lowercase, then print it, so the output is exactly gamer_kid. Remember that string methods return a new string.
Constraint
- Work it out with code. Printing the answer as text doesn't count.
raw = " GaMeR_KiD " raw.strip() print(raw)
PracticePredict the output
Slices of brainlag
Type exactly what this prints.
word = "brainlag"
print(word[0:5])
print(word[-3:])
print(len(word) - 1)
print(word.upper().count("A"))
PracticeComplete the code
Song length label
Replace each ___ so the program prints Neon Rain is 3:27 long. Work the minutes and seconds out from seconds with // and %, inside the f-string.
Constraint
- Work it out with code. Printing the answer as text doesn't count.
song = "Neon Rain" seconds = 207 print(f"___ is ___:___ long")
Your turn
Make a gamer tag
A sign-up form suggests a gamer tag: the first name in lower case, then the first three letters of the surname in lower case, then the last two digits of the birth year. With the values below, print exactly lunaoka11. Build it with slices and string methods, not by typing the answer.
Constraint
- Build the tag from the variables.
On your own. Hints open after your first check.
first = "Luna" last = "Okafor" year = "2011"
Passed
You can now