Format Symbol ของภาษา python

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: Format Symbol ของภาษา python

Format Symbol ของภาษา python

โดย nuattawoot » 25/08/2017 6:26 pm

Format Symbol

โค้ด: เลือกทั้งหมด

%c	character
%s	string conversion via str() prior to formatting
%i	signed decimal integer
%d	signed decimal integer
%u	unsigned decimal integer
%o	octal integer
%x	hexadecimal integer (lowercase letters)
%X	hexadecimal integer (UPPERcase letters)
%e	exponential notation (with lowercase ‘e’)
%E	exponential notation (with UPPERcase ‘E’)
%f	floating point real number
%g	the shorter of %f and %e
%G	the shorter of %f and %E
การใช้ ]%c character (การแปลง สัญลักษณ์)

โค้ด: เลือกทั้งหมด

print "%c" % 'a'
-- a
print ("%c" % 97)
-- a
print ("%c" % 98)
-- b
การใช้ %s string conversion via str() prior to formatting

โค้ด: เลือกทั้งหมด

name = raw_input("who are you?")
print "hello %s" % (name,)
การใช้ %i กับ %d จะทำงานเหมือน

โค้ด: เลือกทั้งหมด

number = 8
print "your number is %i." % number
การใช้ %o octal integer เลขฐาน 8

โค้ด: เลือกทั้งหมด

 print "%o" % 011
-- 11
print "%o" % 8
-- 10 # เพราะ 010 == 8 
การใช้ %x กับ %X แปลงเลขฐาน 16

โค้ด: เลือกทั้งหมด

 print "%x %X" % (255, 255) 
-- ff FF
 
การใช้ %e %E
เขาอาร์กิวเมนต์คู่มีการปัดเศษและแปลงเป็นรูปแบบ [-] d.ddde ± dd ซึ่งมีหนึ่งหลักก่อนอักขระทศนิยมและจำนวนหลักหลังจากที่มีค่าเท่ากับความแม่นยำ หากความแม่นยำขาดหายไปจะใช้เวลาเป็น 6; ถ้าค่าความแม่นยำเป็นศูนย์จะไม่มีตัวอักษรทศนิยมปรากฏขึ้น การแปลง E ใช้ตัวอักษร E (แทน e) เพื่อนำตัวเลขยกกำลัง เลขยกกำลังเสมอประกอบด้วยตัวเลขสองตัว; ถ้าค่าเป็นศูนย์เลขยกกำลังคือ 00

โค้ด: เลือกทั้งหมด

print "%e %E" % (255, 255)
-- 2.550000e+02 2.550000E+02
การใช้ %f

โค้ด: เลือกทั้งหมด

print("%.2f" % 100) #.2f คือการเพิ่มจุดทศนิยมไป 2 ตำแหน่ง
-- 100.00
การใช้ %G %g
อาร์กิวเมนต์คู่ถูกแปลงเป็นแบบ f หรือ e (หรือ F หรือ E สำหรับ Conversion G) ความแม่นยำระบุจำนวนหลักที่มีนัยสำคัญ หากความแม่นยำขาดหายไปจะมี 6 หลัก; ถ้าความแม่นยำเป็นศูนย์จะถือว่าเป็น 1 รูปแบบ e ใช้ถ้าเลขยกกำลังจากการแปลงน้อยกว่า -4 หรือมากกว่าหรือเท่ากับความแม่นยำ ศูนย์ท้ายจะถูกลบออกจากส่วนที่เป็นเศษส่วนของผลลัพธ์ จุดทศนิยมจะปรากฏเฉพาะเมื่อมีตัวเลขอย่างน้อยหนึ่งตัวตามด้วย

โค้ด: เลือกทั้งหมด

print "%g %G" % (1234567, 1234567)
-- 1.23457e+06 1.23457E+06

ข้างบน