Text is everywhere in programming, and Python gives you two things that make working with it a joy: f-strings for fast, readable formatting, and a rich set of string methods for cleaning and transforming text. Master both and you'll write clearer code for everything from log messages to data cleaning to report generation.

This guide covers f-strings end-to-end — embedding expressions, number and date formatting, alignment, and the handy = debug form — then tours the most useful string methods with real examples. Every snippet is runnable with output.

f-strings: The Modern Way to Format

Prefix a string with f and put any expression inside {}. Introduced in Python 3.6, f-strings are faster and far more readable than % or .format().

name = "Tushar"
age = 25
print(f"My name is {name} and I am {age} years old.")

# Any expression works inside the braces
print(f"Next year I'll be {age + 1}.")
print(f"{name.upper()} has {len(name)} letters.")

Output:

My name is Tushar and I am 25 years old.
Next year I'll be 26.
TUSHAR has 6 letters.

Formatting Numbers

Add a format spec after a colon: {value:spec}. This controls decimals, thousands separators, percentages, and more.

pi = 3.14159265
price = 1234567.891

print(f"{pi:.2f}")          # 2 decimal places
print(f"{price:,.2f}")      # thousands separator + 2 dp
print(f"{0.1234:.1%}")      # percentage
print(f"{255:#x}")          # hexadecimal
print(f"{42:08.2f}")        # zero-padded, width 8

Output:

3.14
1,234,567.89
12.3%
0xff
00042.00

Alignment and Width

Use < (left), > (right), and ^ (center) with a width — great for tidy tables in the terminal.

items = [("Apple", 3), ("Banana", 12), ("Cherry", 1)]
for name, qty in items:
    print(f"{name:<10}|{qty:>5}")

Output:

Apple     |    3
Banana    |   12
Cherry    |    1

The = Debug Shortcut

Since Python 3.8, adding = inside the braces prints both the expression and its value — perfect for quick debugging.

x = 10
y = 20
print(f"{x=}, {y=}, {x + y=}")

Output:

x=10, y=20, x + y=30

Essential String Methods: Case & Whitespace

text = "  Hello World  "
print(text.strip())          # remove surrounding whitespace
print(text.strip().lower())  # lowercase
print("python".upper())
print("hello world".title()) # Title Case
print("Hello".replace("l", "L"))

Output:

Hello World
hello world
PYTHON
Hello World
HeLLo

Splitting and Joining

split() breaks a string into a list; join() stitches a list back into a string. This pair handles most text parsing.

csv_line = "Tushar,25,Surat"
parts = csv_line.split(",")
print(parts)

words = ["learn", "python", "today"]
print(" ".join(words))
print("-".join(words))

Output:

['Tushar', '25', 'Surat']
learn python today
learn-python-today

Searching and Checking

email = "user@example.com"
print(email.startswith("user"))
print(email.endswith(".com"))
print("@" in email)                 # membership test
print(email.find("@"))              # index of @ (-1 if absent)
print("12345".isdigit())
print("Hello".isalpha())

Output:

True
True
True
4
True
True

Real-World Example: Formatting a Receipt

Combining f-string alignment and number formatting to print an aligned receipt.

cart = [("Coffee", 4.5), ("Sandwich", 8.25), ("Cookie", 2.0)]
total = 0

print(f"{'Item':<12}{'Price':>8}")
print("-" * 20)
for item, price in cart:
    print(f"{item:<12}{price:>8.2f}")
    total += price
print("-" * 20)
print(f"{'TOTAL':<12}{total:>8.2f}")

Output:

Item           Price
--------------------
Coffee          4.50
Sandwich        8.25
Cookie          2.00
--------------------
TOTAL          14.75

Common Mistakes to Avoid

  • Forgetting the f prefix — without it, {name} prints literally.
  • Thinking strings are mutable — methods like replace() return a new string; reassign the result.
  • Building strings with + in a loop — use "".join(list), which is much faster.
  • Using backslashes inside f-string braces (before Python 3.12) — precompute the value instead.
  • Confusing split() with no args vs a separator — bare split() splits on any whitespace and drops blanks.

Summary Table

TaskCodeResult
Insert valuef"{x}"value of x
2 decimalsf"{x:.2f}"3.14
Thousandsf"{x:,}"1,000,000
Align left/rightf"{x:<10}" / {x:>10}padded text
Debugf"{x=}"x=10
Split / joins.split(',') / ','.join(lst)list / string

Conclusion

f-strings make formatting readable and fast, while string methods give you a complete toolkit for cleaning and transforming text. Learn the format-spec mini-language (:.2f, :,, alignment) and the core methods (strip, split, join, replace, startswith), and almost every text task becomes a one-liner.

Practice by reformatting a messy list of names — strip, title-case, and align them into a neat column with a single f-string.