Extract, format and clean text like in a real project thanks to slicing, f-strings and string methods.
Open this lesson in KodokonIn a real project, you manipulate strings constantly: order references, email addresses, file lines. Slicing extracts a substring with the [start:stop:step] syntax: the stop index is excluded, negative indices count from the end, and omitting a bound means "from the start" or "to the end".
reference = "ORD-2026-00042"
print(reference[:3]) # ORD
print(reference[4:8]) # 2026
print(reference[-5:]) # 00042
print(reference[::-1]) # 24000-6202-DROF-strings are the modern way to build text: prefix the string with f and insert expressions inside curly braces. The format specification after the colon controls the display: :.2f rounds to two decimals, :03d pads with zeros. In practice, abandon concatenation with +: the f-string is more readable and avoids type errors.
product = "wireless keyboard"
price = 49.9
stock = 3
print(f"{product} : {price:.2f} EUR")
print(f"Stock : {stock:03d} units")
total = price * stock
print(f"Total : {total:.2f} EUR")String methods cover the essentials of data cleaning: strip removes surrounding whitespace, split breaks into a list, join glues back together, lower and upper normalize case, replace substitutes, startswith and endswith test the ends. Key point: strings are immutable, each method returns a new string without modifying the original.
raw = " Alice.Martin@Example.COM ; ADMIN "
email, role = raw.split(";")
email = email.strip().lower()
role = role.strip().lower()
print(email) # alice.martin@example.com
print(role) # admin
print(email.endswith("@example.com")) # True