Advertisement
❮ Previous: Python Exception Handling Next: Python Expressions ❯

Python Strings & String Formatting

Mastering strings and string formatting is essential for clean, readable, and professional Python code. Because strings are immutable (they cannot be changed in-place after creation), Python provides a rich set of built-in methods and formatting techniques to manipulate, inspect, and display text efficiently.


1. String Basics, Indexing, & Slicing

Strings in Python are arrays of unicode characters. You can define them using single ('...'), double ("..."), or triple ("""...""" or '''...''') quotes for multi-line text.

text = "Hello, Python!"

# Indexing (0-based from start, -1 from end)
print(text[0])   # Output: H
print(text[-1])  # Output: !

# Slicing [start:end:step]
print(text[7:13])  # Output: Python
print(text[::-1])  # Output: !nohtyP ,olleH (Reversed string)

Try this code ❯


Advertisement

2. Essential String Methods

Python strings come with dozens of built-in methods that return new strings without modifying the original.

Method Description Example
upper() / lower() Converts case "Hello".upper() --> "HELLO"
strip() Removes leading/trailing whitespace " text ".strip() --> "text"
replace(old, new) Replaces occurrences of a substring "I like cats".replace("cats", "dogs")
split(sep) Splits string into a list by separator "apple,banana,grape".split(",")
join(iterable) Joins elements of an iterable into a string "-".join(["2026", "06", "06"])
find(sub) Returns lowest index of substring (or -1) "Python".find("th") --> 2

Advertisement

3. String Formatting Techniques

As Python evolved, formatting text dynamically improved significantly. Here are the three main approaches:

A. Old-Style Formatting (% Operator)

Borrowed from C, this uses format specifiers like %s (string), %d (integer), and %.2f (float with 2 decimal places). It is largely considered legacy syntax.

name = "Alice"
score = 95.567
print("Hello %s, your score is %.2f" % (name, score))
# Output: Hello Alice, your score is 95.57

Try this code ❯

B. The .format() Method

Introduced in Python 3, this uses curly braces {} as placeholders. It supports positional and keyword arguments, making it more flexible.

# Positional and Keyword arguments
print("Hello {}, you have {} unread messages.".format("Bob", 3))
print("Hello {name}, your balance is ${balance:.2f}".format(name="Charlie", balance=150.5))

Try this code ❯

C. Modern f-strings (Literal String Interpolation)

Introduced in Python 3.6, f-strings (f"..." or F"...") are the modern standard. They evaluate expressions at runtime directly inside the string and offer superior readability, performance, and power.

name = "Diana"
items = 4
total_cost = 45.895

# Direct variable insertion and expression evaluation
print(f"User {name} purchased {items} items. Total: ${total_cost:.2f}")
# Output: User Diana purchased 4 items. Total: $45.90

# Evaluating code expressions inline
print(f"Next year, you will be {2026 + 1} years old.")

# Debugging shortcut using '='
x = 10
y = 25
print(f"{x=}, {y=}, {x + y=}")
# Output: x=10, y=25, x+y=35

Try this code ❯

❮ Previous: Python Exception Handling Next: Python Expressions ❯
Advertisement