Python có 3 cách format chuỗi (interpolation):
- % (old style): Python 2/3.
"%s %d" % ("abc", 123) - .format() (new style): Python 2.6+.
"{} {}".format("abc", 123) - f-strings: Python 3.6+.
f"{var} {expr}"(khuyến nghị).
Chi tiết
Old style %: Hỗ trợ %s, %d, %x, %f, %e, %g, %%. Căn chỉnh: %5s, %-7s, %5.7s.
.format(): Hỗ trợ positional {0}, {1}, named {name}, dict unpacking. Căn chỉnh: {:<5}, {:^10}, {:>10}.
f-strings: Viết biểu thức trực tiếp trong {}, hỗ trợ format spec: {val:.2f}, {text:.<10}.
Ví dụ f-strings
player = 'Roger_Federer'
country = 'Legend'
titles = 20
print(f"Tennis player {player} From {country} had won {titles} titles")
print(f"I hope {player} wins another {titles - 10} titles")
print(f"{'*'*3} Tennis player {player.upper()} From {country:.^10} had won {titles} titles")
Kết luận
f-strings dễ đọc, hiệu năng tốt, là chuẩn hiện đại.