Python มี 3 วิธีจัดรูปแบบสตริง:
%- รูปแบบเก่า (Python 2, 3).format()- รูปแบบใหม่ (Python 2.6+)f-strings- ล่าสุด (Python 3.6+) แนะนำให้ใช้
1. รูปแบบ % (Old Style)
print('Number: %s' % 42)
print('Hex: %x' % 42)
print('Float: %g' % 42)
player = 'Roger Federer'
country = 'Legend'
titles = 20
print('Player %s from %s has %d titles' % (player, country, titles))
# Alignment: %-10s (left), %10s (right), %5.7s (width.precision)
2. รูปแบบ .format() (New Style)
print('Player {} from {} has {} titles'.format(player, country, titles))
print('Player {1} from {2} has {0} titles'.format(titles, player, country))
print('Player {player} from {country} has {titles} titles'.format(
player='Roger Federer', country='Legend', titles=20))
print('Player {0} from {1:<10} has {2:>5} titles'.format(player, country, titles))
# Alignment: < (left), > (right), ^ (center)
3. f-strings (Modern, แนะนำ)
player = 'Roger_Federer'
country = 'Legend'
titles = 20
print(f'Player {player} from {country} has {titles} titles')
print(f'I hope {player} wins another {titles - 10} titles')
print(f'{"*" * 3} Player {player.upper()} from {country:.^10} has {titles} titles')
ทำไม f-strings ดีกว่า
- อ่านง่าย เร็วกว่า รองรับ expression ภายใน {} เรื่อง index offset (เริ่มที่ 1 แทน 0) ทำได้ง่าย:
f'{i+1}: {player.title()}'
สรุป
ใช้ f-strings สำหรับ Python 3.6+ จะได้โค้ดสะอาด มีประสิทธิภาพ และอ่านง่ายที่สุด