Strings and Formatting
Python has many string operations, but the ones that are truly common and worth building muscle memory for aren't that many. This page is split into two parts:
- How to handle strings themselves
- How to format strings for output
Basic Operations
text = "hello"
print(len(text))
print(text[0])
print(text[1:4])
print(text.upper())
print(text.replace("ll", "LL"))
Strings are immutable objects, so these methods return new strings and don't modify the original in place.
Common Concatenation Methods
first = "hello"
second = "world"
print(first + " " + second)
print(" ".join([first, second]))
When repeatedly concatenating multiple fragments, join() is generally preferred.
f-string
This is my default recommended formatting approach:
name = "alice"
score = 95.1234
print(f"{name}: {score:.2f}")
Advantages:
- High readability
- You can write expressions directly
- The relationship with variables is very clear
str.format()
name = "alice"
score = 95.1234
print("{}: {:.2f}".format(name, score))
Still commonly seen today, but unless you need backward compatibility, I prefer using f-strings directly.
Legacy % Formatting
name = "alice"
age = 20
print("%s is %d years old." % (name, age))
Still seen in older projects, but new code generally doesn't prioritize this approach.
Common Format Controls
value = 3.14159
print(f"{value:.2f}") # 3.14
print(f"{value:8.2f}") # width 8, 2 decimal places
print(f"{42:04d}") # 0042
A frequently encountered detail: round() and formatting are not the same thing
round(x, 2): Changes the numeric valuef"{x:.2f}": Emphasizes output format
If you need to "strictly display two decimal places", prefer formatting the string.
Practices I recommend
- Default to f-strings first
- Prefer
join()for multi-part string concatenation - When you need to look up methods, see Common String Methods