2.2 Strings and Formatting
Strings (str) are immutable Unicode sequences. Python provides multiple official formatting styles.
String fundamentals
- Supports indexing and slicing like other sequences.
- Rich methods include
split(),join(),strip(),replace(),find(),partition(). - Most string operations return new strings (immutability).
Formatting options
1) Formatted string literals (f-strings)
name = "Sarfaraz"
score = 95
print(f"{name} scored {score}")
2) str.format()
print("{} scored {}".format("Sarfaraz", 95))
3) %-style formatting (legacy style)
print("%s scored %d" % ("Sarfaraz", 95))
Recommended practice
- Prefer f-strings for readability and direct expression embedding.
- Use
str.format()for reusable templates. - Use
%-style only when maintaining legacy code.
Official references
strand methods: https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str- Format mini-language: https://docs.python.org/3/library/string.html#formatspec
- f-strings (tutorial): https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals