Kodokon kodokon.com

Strings in depth: slicing, f-strings, methods

Extract, format and clean text like in a real project thanks to slicing, f-strings and string methods.

8 min · 3 questions

Open this lesson in Kodokon

In 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".

PYTHON
reference = "ORD-2026-00042"

print(reference[:3])    # ORD
print(reference[4:8])   # 2026
print(reference[-5:])   # 00042
print(reference[::-1])  # 24000-6202-DRO
Slicing splits a reference without writing a single loop.

F-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.

PYTHON
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")
Format specifications guarantee a clean display of numbers.

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.

PYTHON
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
Chaining strip, lower and split: the data-cleaning trio.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is the value of "python"[1:4]?
    • pyt
    • yth
    • ytho
    • pyth
  2. What does print(f"{3.14159:.2f}") display?
    • 3.14
    • 3.1415
    • 3,14
    • 0.14
  3. What does "a,b,c".split(",") return?
    • The string 'abc'
    • The list ['a', 'b', 'c']
    • The tuple ('a', 'b', 'c')