Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 4

Strings: working with text

FreeLesson 6 of 78

Names, cities, statuses, file paths and log lines are all text. In Python text is called a string (str).

BUILD, MEASURE, SLICEPYTHON 3.12
name = "Aarav"
city = 'Bengaluru'                 # single or double quotes
print(name + " from " + city)      # + joins strings
print("-" * 20)                    # * repeats
print(len(name))                   # number of characters

print(name[0], name[-1])           # first and last character
print(city[0:4], city[4:])         # slices: [start:stop]

Output

Aarav from Bengaluru
--------------------
5
A v
Beng aluru
THE METHODS YOU WILL USE EVERY DAYPYTHON 3.12
status = "  Delivered  "
print("[" + status.strip() + "]")        # remove outer spaces
print(status.strip().lower())            # small letters
print("delivered".upper(), "pune".title())
print("2025-04-01".replace("-", "/"))
print("101,1,delivered".split(","))       # text -> list
print(" | ".join(["a", "b", "c"]))       # list -> text
print("deliver" in "delivered", "orders.csv".endswith(".csv"))

Output

[Delivered]
delivered
DELIVERED Pune
2025/04/01
['101', '1', 'delivered']
a | b | c
True True
F-STRINGS: THE CLEAN WAY TO BUILD TEXTPYTHON 3.12
name, orders, revenue = "Diya", 3, 4143.0
print(f"{name} placed {orders} orders worth {revenue}")
print(f"{revenue:,.2f}")          # thousands separator, 2 decimals
print(f"{orders:03d}")            # pad with zeros: 003
print(f"{name:<8}|{name:>8}|")    # align left / right in 8 spaces
print(f"{0.256:.1%}")             # as a percentage

Output

Diya placed 3 orders worth 4143.0
4,143.00
003
Diya    |    Diya|
25.6%

Put an f before the quotes and any variable inside { } is filled in. After a colon you can format it: decimals, commas, padding, percent.

Try it yourself before moving on

  1. Print the first 3 letters of "Hyderabad".
  2. Turn "order_date" into "Order Date" (replace and title).
  3. Count the letter "a" in "Bengaluru" with .count("a").

Watch the free lesson

The same topic in the Free Lessons library, free with a sign-in.