Python String Formatting
By Seokhyeon Byun 3 min read
Note: This post is based on my old programming study notes when I taught myself.
String Formatting
After understanding data types in Python, it is important to know how to format them properly.
Method 1: Old formatting using %
%d: integer%s: string%f: float%c: character
number = 3
day = "several"
y = 'I ate %d apples. So I was happy for %s days.' % (number, day)
print(y)
# Output: I ate 3 apples. So I was happy for several days.
Method 2: Using {} with .format()
Case 1: Direct way
x = "I like {} very much".format('coding')
print(x)
# Output: I like coding very much
Case 2: Using variables inside string
x = 'I like {name} very much'.format(name="Python")
print(x)
# Output: I like Python very much
Advanced .format() usage:
# Multiple variables
text = "My name is {name} and I am {age} years old".format(name="Alice", age=25)
# Positional arguments
text = "The {0} is {1} years old".format("cat", 5)
# Number formatting
price = 49.95
text = "The price is {:.2f}".format(price) # Output: The price is 49.95
Method 3: Using f-strings (Python 3.6+)
name = 'Elon Musk'
age = 52
z = f"This is {name}."
print(z)
# Output: This is Elon Musk.
# More examples
greeting = f"Hello, {name}! You are {age} years old."
calculation = f"2 + 3 = {2 + 3}"
formatted_number = f"Pi is approximately {3.14159:.2f}"
Escape Characters
Escape characters allow you to include special characters in strings that would otherwise be difficult to represent.
Common Escape Characters
- Double quote:
\" - Single quote:
\' - Backslash:
\\ - Newline:
\n - Tab:
\t - Carriage return:
\r
Examples
# Including quotes in strings
text1 = "He said, \"Hello World!\""
text2 = 'It\'s a beautiful day'
# Backslash in path
path = "C:\\Users\\Documents\\file.txt"
# Multi-line strings with newline
message = "First line\nSecond line\nThird line"
# Tab spacing
table = "Name\tAge\tCity"
Raw Strings
Use raw strings (prefix with r) to avoid interpreting escape characters:
# Regular string with escape characters
path1 = "C:\\Users\\Documents"
# Raw string - backslashes are treated literally
path2 = r"C:\Users\Documents"
# Both produce the same result but raw strings are cleaner for paths
Quick Reference
| Method | Syntax | Example | Best Use Case |
|---|---|---|---|
| % formatting | "text %s" % value | "Hello %s" % name | Legacy code |
| .format() | "text {}".format(value) | "Hello {}".format(name) | Python 2.7+ compatibility |
| f-strings | f"text {value}" | f"Hello {name}" | Modern Python (3.6+) - Recommended |
Recommendation: Use f-strings for new code as they are more readable, faster, and less error-prone.