Indexing, Slicing & f-Strings
Extract characters with 0-based indexing, slice substrings with [start:stop:step], and format text with f-strings.
Learning objectives
- Access individual string characters using positive and negative indices
- Extract substrings using slice notation [start:stop:step]
- Use f-strings for clean variable interpolation
Lesson material
Indexing & Slicing
Strings are ordered sequences of immutable characters.
- Positive Index: Starts from
0at the beginning. - Negative Index: Starts from
-1at the last character. - Slice Notation:
string[start:stop:step](stop index is EXCLUSIVE).
Example code
text = "PythonCode"
# Indexing
print("First char:", text[0]) # P
print("Last char:", text[-1]) # e
# Slicing
print("First 6 chars:", text[0:6]) # Python
print("Reversed:", text[::-1]) # edoCnohtyP
f-Strings (Formatted String Literals)
Prefix strings with f or F to embed Python expressions directly inside curly braces {}.
Example code
name = "Rimon"
score = 98.5
print(f"Student {name} achieved a score of {score}%.")
Practice exercise: String Slicing & Formatting
Given `word = "DEVELOPER"`, extract the substring `"DEV"` (first 3 chars) and print `f"Prefix: {sub}"`.
Test yourself with the Module 3: Strings & String Operations quiz →