Beginner 5 min
Strings, slices, and formatting
A string is text you can inspect, slice, and combine to make a message.
How it works
Start by writing a position over each letter. For Mira use M=0, i=1, r=2, a=3. A slice has two boundaries. [1:3] starts at i and stops just before a; it gives ir. A string itself stays the same after slicing.
Walk through an example
name = "Mira" stores four characters. name[0] is M, name[1:3] is ir, and f"Hi {name}" inserts the whole name into a greeting.
What to watch for
A slice excludes its stop index. A single index outside the string raises an error, while an out-of-range slice stops at the available boundary.
Code example
name = "Mira"
print(name[1:3])
print(f"Hi {name}")Check your understanding
Which characters does this slice return?
See the example and explanation
- Worked example
- Given
'green'[1:4] - Answer
ree
The characters at positions 1, 2, and 3 are r, e, and e. The character at position 4 is excluded.