มีหลายวิธีแสดงผลลัพธ์ของโปรแกรม: พิมพ์ในรูปแบบอ่านง่าย หรือเขียนลงไฟล์ บางครั้งต้องการควบคุมรูปแบบ output มากกแค่ print คั่นด้วย space
วิธีการจัดรูปแบบ Output
- f-strings (Python 3.6+): เริ่มสตริงด้วย f หรือ F ก่อนเครื่องหมายคำพูด
- str.format() (Python 2.6+): ใช้ {} วางตำแหน่งตัวแปร รองรับ formatting directives
- String slicing/concatenation: ใช้ string methods เช่น center(), ljust(), rjust()
- % operator (printf-style): ใช้ % formatting
1. String Modulo Operator (%)
# % operator สำหรับ string formatting
print("Vishesh : %2d, Portal : %5.2f" % (1, 5.333))
print("Total students : %3d, Boys : %2d" % (240, 120))
print("%7.3o" % (25)) # Octal
print("%10.3E" % (356.08977)) # Exponential
ผลลัพธ์
Vishesh : 1, Portal : 5.33
Total students : 240, Boys : 120
031
3.561E+02
Format Specifiers พบบ่อย
| Specifier | คำอธิบาย |
| %d, %i | Signed decimal integer |
| %f, %F | Fixed point decimal |
| %e, %E | Scientific notation |
| %g, %G | General format (auto) |
| %o | Octal |
| %x, %X | Hexadecimal |
| %s | String |
| %r | repr() output |
| %% | Literal % |
2. Format Method (str.format())
# Dictionary formatting
tab = {'Vishesh': 4127, 'for': 4098, 'python': 8637678}
print('Vishesh: {0[Vishesh]:d}; For: {0[for]:d}; python: {0[python]:d}'.format(tab))
# Keyword arguments
data = dict(fun="VisheshforPython", adj="Python")
print("I love {fun} computer {adj}".format(**data))
# Positional arguments
print("{} {} {}".format("a", "b", "c"))
# Named placeholders
print("{name} is {age} years old".format(name="John", age=30))
# Formatting numbers
print("{:.2f}".format(3.14159)) # 3.14
print("{:>10}".format("test")) # Right align (width 10)
print("{:<10}".format("test")) # Left align
print("{:^10}".format("test")) # Center
print("{:,}".format(1000000)) # 1,000,000 (thousands separator)
print("{:%Y-%m-%d}".format(datetime.now())) # Date formatting
3. String Methods (Alignment & Padding)
cstr = "I love python"
# Center aligned with fill character
print("Center aligned with fillchr:")
print(cstr.center(40, '$'))
# Left aligned with padding
print("Left aligned:")
print(cstr.ljust(40, '-'))
# Right aligned with padding
print("Right aligned:")
print(cstr.rjust(40, '-'))
# zfill - zero fill (สำหรับตัวเลข)
print("42".zfill(6)) # 000042
print("-42".zfill(6)) # -00042
ผลลัพธ์
Center aligned with fillchr:
$$$$$$$$$$$$$I love python$$$$$$$$$$$$$$
Left aligned:
I love python---------------------------
Right aligned:
---------------------------I love python
4. f-strings (แนะนำสำหรับ Python 3.6+)
name = "Vishesh"
age = 25
score = 95.666
# Basic
print(f"Name: {name}, Age: {age}")
# Formatting
print(f"Score: {score:.2f}") # 95.67
print(f"Score: {score:>10.2f}") # Right align width 10
print(f"Score: {score:<10.2f}") # Left align
print(f"Score: {score:^10.2f}") # Center
print(f"Number: {1000000:,}") # 1,000,000
print(f"Hex: {255:#x}") # 0xff
print(f"Binary: {42:#b}") # 0b101010
# Expressions
print(f"Sum: {10 + 20}") # 30
print(f"Upper: {name.upper()}") # VISHESH
# Debugging (Python 3.8+)
print(f"{name=}, {age=}") # name='Vishesh', age=25
สรุป: ควรใช้วิธีไหน?
| วิธี | Python Version | แนะนำสำหรับ |
| f-strings | 3.6+ | ทุกกรณี (เร็วที่สุด อ่านง่าย) |
| str.format() | 2.6+ | รองรับ Python เก่า, dynamic format strings |
| % operator | All | Legacy code, logging, simple cases |
| String methods | All | Alignment/padding เฉพาะเจาะจง |
Best Practice
- ใช้ f-strings เป็นหลัก (Python 3.6+)
- ใช้ str.format() เมื่อ format string มาจาก config/file/user input
- หลีกเลี่ยง % operator ในโค้ดใหม่
- ใช้ string methods (center, ljust, rjust) สำหรับ text alignment พิเศษ