Skip to main content

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))
  • Prefer f-strings for readability and direct expression embedding.
  • Use str.format() for reusable templates.
  • Use %-style only when maintaining legacy code.

Official references