Strings in Depth
Indexing, slicing, the methods you'll use constantly, and f-strings.
A string is an ordered, immutable sequence of characters — you can index and slice it like a list, but you can never change a character in place.
channel = "CodeWithMunnaX"
print(channel[0]) # 'C' -- first character
print(channel[-1]) # 'X' -- last character
print(channel[4:8]) # 'ithM' -- slice: [start:stop), stop excluded
print(channel[::-1]) # 'XnuMhtiWedoC' -- reversed
channel[0] = "K" raises TypeError: 'str' object does not support item assignment — to "change" a string you build a new one.
f-strings — the modern way to format text
An f-string embeds expressions directly inside {}, evaluated at runtime. This is the standard way to build strings in modern Python — prefer it over + concatenation or %-formatting.
channel = "CodeWithMunnaX"
subscribers = 250_000
print(f"{channel} has {subscribers:,} subscribers")
# CodeWithMunnaX has 250,000 subscribers
price = 199.999
print(f"Price: ₹{price:.2f}") # Price: ₹200.00 -- format spec rounds to 2 decimals
Methods you'll reach for constantly
text = " Learn Python with CodeWithMunnaX "
print(text.strip()) # removes leading/trailing whitespace
print(text.lower()) # lowercase
print(text.upper()) # UPPERCASE
print(text.strip().replace("Learn", "Master"))
print(text.strip().split(" ")) # ['Learn', 'Python', 'with', 'CodeWithMunnaX']
print("-".join(["2024", "01", "15"])) # '2024-01-15'
print("Python" in text) # True -- substring check with 'in'
print(text.strip().startswith("Learn"))
Strings are iterable
for letter in "abc":
print(letter)Key points to remember
- •Strings are immutable — every 'modifying' method (upper, replace, strip...) returns a new string, it doesn't change the original.
- •Slicing is [start:stop:step] and never raises an error even outside the string's bounds; step -1 reverses it.
- •f-strings (f"{expr}") are the modern, preferred way to build strings — they support format specs like {value:.2f} and {value:,}.
- •'substring' in text is the idiomatic way to check containment.
- •split() turns a string into a list of parts; join() does the reverse, gluing a list into one string.
f-strings, slicing, and common methods
Revision Flashcards
Tap a card to flip it and see the answer.