Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - การจัดรูปแบบเอาต์พุต


มีหลายวิธีในการนำเสนอผลลัพธ์ของโปรแกรม สามารถพิมพ์ข้อมูลในรูปแบบที่มนุษย์อ่านได้ หรือเขียนลงในไฟล์เพื่อใช้ในอนาคต บางครั้งผู้ใช้มักต้องการควบคุมการจัดรูปแบบเอาต์พุตมากกว่าแค่การพิมพ์ค่าที่คั่นด้วยช่องว่าง มีหลายวิธีในการจัดรูปแบบเอาต์พุต

  • หากต้องการใช้ตัวอักษรสตริงที่จัดรูปแบบ ให้เริ่มสตริงด้วย f หรือ F ก่อนเครื่องหมายอัญประกาศเปิดหรือเครื่องหมายอัญประกาศ
  • เมธอด str.format() ของสตริงช่วยให้ผู้ใช้ได้ผลลัพธ์ที่ดีกว่า
  • ผู้ใช้สามารถจัดการสตริงทั้งหมดได้โดยใช้การแยกสตริงและการดำเนินการต่อกันเพื่อสร้างเลย์เอาต์ที่ผู้ใช้ต้องการ ประเภทสตริงมีวิธีการบางอย่างที่ดำเนินการที่เป็นประโยชน์สำหรับการขยายสตริงตามความกว้างของคอลัมน์ที่กำหนด

การจัดรูปแบบเอาต์พุตโดยใช้ตัวดำเนินการโมดูลัสสตริง (%)

สามารถใช้ตัวดำเนินการ % สำหรับการจัดรูปแบบสตริงได้เช่นกัน มันตีความอาร์กิวเมนต์ด้านซ้ายเหมือนกับสตริงรูปแบบรูปแบบ printf() ที่จะนำไปใช้กับอาร์กิวเมนต์ที่ถูกต้อง

ตัวอย่าง

# string modulo operator(%) to print
# print integer and float value
print("Vishesh : % 2d, Portal : % 5.2f" %(1, 05.333))
# print integer value
print("Total students : % 3d, Boys : % 2d" %(240, 120))
# print octal value
print("% 7.3o"% (25))
# print exponential value
print("% 10.3E"% (356.08977))

ผลลัพธ์

Vishesh : 1, Portal : 5.33
Total students : 240, Boys : 120
031
3.561E+02

การจัดรูปแบบเอาต์พุตโดยใช้วิธีการจัดรูปแบบ

เพิ่มเมธอด format() ใน Python(2.6) วิธีการจัดรูปแบบสตริงต้องใช้ความพยายามด้วยตนเองมากขึ้น ผู้ใช้ใช้ {} เพื่อทำเครื่องหมายตำแหน่งที่ตัวแปรจะถูกแทนที่และสามารถให้คำสั่งการจัดรูปแบบโดยละเอียด แต่ผู้ใช้ยังต้องให้ข้อมูลเพื่อจัดรูปแบบ

ตัวอย่าง

# show format () is used in dictionary
tab = {'Vishesh': 4127, 'for': 4098, 'python': 8637678}
# using format() in dictionary
print('Vishesh: {0[vishesh]:d}; For: {0[for]:d}; '
'python: {0[python]:d}'.format(tab))
data = dict(fun ="VisheshforPython", adj ="Python")
# using format() in dictionary
print("I love {fun} computer {adj}".format(**data))

การจัดรูปแบบเอาต์พุตโดยใช้วิธีสตริง

ในเอาต์พุตนี้ถูกจัดรูปแบบโดยใช้การแยกสตริงและการดำเนินการต่อกัน

ตัวอย่าง

# format a output using string() method
cstr = "I love python"
# Printing the center aligned
# string with fillchr
print ("Center aligned string with fillchr: ")
print (cstr.center(40, '$'))
# Printing the left aligned string with "-" padding
print ("The left aligned string is : ")
print (cstr.ljust(40, '-'))
# Printing the right aligned string with "-" padding
print ("The right aligned string is : ")
print (cstr.rjust(40, '-'))

ผลลัพธ์

Center aligned string with fillchr:
$$$$$$$$$$$$$I love python$$$$$$$$$$$$$$
The left aligned string is :
I love python---------------------------
The right aligned string is :
---------------------------I love python