เมื่อพิมพ์ผลลัพธ์จากการประมวลผลข้อมูลใน Python เราอาจต้องการให้เอาต์พุทอยู่ในรูปแบบที่น่าสนใจหรือมีความแม่นยำทางคณิตศาสตร์ ในบทความนี้เราจะดูว่ามีตัวเลือกต่างๆ อะไรบ้างที่เราสามารถใช้เพื่อเอาต์พุทผลลัพธ์
การใช้ format
ในวิธีนี้เราใช้ฟังก์ชัน built-in ที่ชื่อ format เราใช้ {} สำหรับ placeholder ของค่าที่จะถูกส่งมาโดย format โดยค่าเริ่มต้นตำแหน่งจะถูกเติมในลำดับเดียวกับค่าที่มาจากฟังก์ชัน format แต่เราสามารถบังคับค่าได้ในแง่ของตำแหน่งเริ่มจาก 0 เป็นดัชนี
ตัวอย่าง
weather = ['sunny','rainy']
day = ['Mon','Tue','Thu']
print('on {} it will be {}'.format(day[0], weather[1]))
print('on {} it will be {}'.format(day[1], weather[0]))
print('on {} it will be {}'.format(day[2], weather[1]))
# Using positions
print('on {0} it will be {1}'.format(day[0], weather[0]))
print('It will be {1} on {0}'.format(day[2], weather[1]))
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
on Mon it will be rainy on Tue it will be sunny on Thu it will be rainy on Mon it will be sunny It will be rainy on Thu
การใช้ %
วิธีนี้เหมาะสมสำหรับนิพจน์ทางคณิตศาสตร์ เราสามารถจัดการจำนวนทศนิยมที่จะแสดง หรือพิมพ์เฉพาะส่วนทศนิยมของ float เรายังสามารถแปลงตัวเลขที่กำหนดเป็นฐานแปดหรือค่าลำดับชี้กำลังได้เช่นในสัญกรณ์ทางวิทยาศาสตร์
ตัวอย่าง
# Print decimals
print("Average age is %1.2f and height of the groups %1.3f" %(18.376, 134.219))
# Print integers
print("Average age is %d and height of the groups %d" %(18.376, 134.219))
# Print octal value
print("% 2.7o" % (25))
# print exponential value
print("% 7.4E" % (356.08977))
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
Average age is 18.38 and height of the groups 134.219 Average age is 18 and height of the groups 134 0000031 3.5609E+02
การจัดตำแหน่งสตริง
เราสามารถจัดตำแหน่งเอาต์พุทที่เป็นสตริงได้โดยใช้ฟังก์ชันสตริง ljust, rjust หรือ center นอกจากสตริงอินพุทแล้ว พวกมันยังรับค่าอีกค่าหนึ่งซึ่งใช้สำหรับ padding การจัดตำแหน่ง
ตัวอย่าง
strA = "Happy Birthday !" # Aligned at center print(strA.center(40, '~'), '\n') # Printing left aligned print(strA.ljust(40, 'x'), '\n') # Printing right aligned print(strA.rjust(40, '^'), '\n')
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
~~~~~~~~~~~~Happy Birthday !~~~~~~~~~~~~ Happy Birthday !xxxxxxxxxxxxxxxxxxxxxxxx ^^^^^^^^^^^^^^^^^^^^^^^^Happy Birthday !