21 เมษายน 2558

Published เมษายน 21, 2558 by with 0 comment

String formatting ใน Python

ในการดึงข้อมูลจากสตริงมาเรียกใช้งาน เราสามารถเรียกใช้งานได้โดยอาศัยตัวแทนชนิดของข้อมูล โดยมีตัวแทนชนิดของข้อมูลดังนี้

%s - สตริง เช่น ข้อความ (str)
%d - จำนวนเต็ม (int)
%f - เลขทศนิยม (float)
%.f - เลขทศนิยมมีจำนวนคงตัวเลขทางด้านขวาของจุดทศนิยม
%x/%X - จำนวนเต็มใน hex แทน (พิมพ์เล็ก/ใหญ่)
%r สำหรับการดีบักข้อมูล

ในบทความนี้จะพูดถึงเรื่อง String formatting ใน Python ครับ

ในภาษา Python มี String formatting 2 แบบด้วยกัน

  1. ตัวแทนชนิดข้อมูล
  2. String formatting

String formatting  Python เบื้องต้น


จากตัวแทนชนิดของข้อมูล เราสามารถใช้ดึงข้อมูลมาไว้ในที่ ที่ต้องการได้ เช่น
ตัวแทนชนิดข้อมูล
name = "Ton"
text = "My name is %s" % name
print(text)
ผลลัพธ์
My name is Ton

String formatting
name = "Ton"
text = "My name is {}".format(name)
print(text)
ผลลัพธ์
My name is Ton

ตัวแทนชนิดข้อมูล
>>> '%s, %s, %s'%('a', 'b', 'c')
'a, b, c'

String formatting
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # สำหรับ Python 3.1 ขึ้นไป
'a, b, c'
หากต้องการเรียงข้อมูลตามที่ต้องการ ไม่สามารถใช้ตัวแทนชนิดข้อมูลได้ครับ ต้องใช้ String formatting ดังนี้
>>> '{2}, {1}, {0}'.format(*'abc') # แยกลำดับของอาร์กิวเมนต์
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')
'abracadabra'
นอกจากนั้น ใน String formatting สามารถเข้าถึงข้อมูลจากอาร์กิวเมนต์ด้วย name ได้ดังนี้
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
สามารถเข้าถึงแอตทริบิวต์ของอาร์กิวเมนต์:
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

อ่านเอกสารเพิ่มเติมได้ที่ docs.python.org/3/library/string.html#format-string-syntax และ pyformat.info
ติดตามบทความต่อไปนะครับ
ขอบคุณครับ

0 ความคิดเห็น:

แสดงความคิดเห็น

แสดงความคิดเห็นได้ครับ :)