โมดูล string และค่าคงที่
ใน Python มีไลบรารีมาตรฐานชื่อ string ซึ่งประกอบด้วยค่าคงที่ เมธอด และคลาสต่างๆ ที่เกี่ยวข้องกับสตริง
เพื่อใช้งาน โมดูลนี้ต้องนำเข้า (import) ก่อน:
import string
ค่าคงที่สำคัญและค่าที่เก็บอยู่:
| ลำดับ | ค่าคงที่และค่า |
|---|---|
| 1 | string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' |
| 2 | string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 3 | string.ascii_letters การรวม ascii_lowercase และ ascii_uppercase: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 4 | string.digits '0123456789' |
| 5 | string.hexdigits '0123456789abcdefABCDEF' |
| 6 | string.octdigits '01234567' |
| 7 | string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' |
| 8 | string.printable อักขระ ASCII ที่พิมพ์ได้ทั้งหมด รวมตัวอักษร สัญลักษณ์ ตัวเลข และ whitespace |
| 9 | string.whitespace '\t\n\r\x0b\x0c' |
ตัวอย่างโค้ด
import string
print(string.hexdigits)
print(string.ascii_uppercase)
print(string.printable)
ผลลัพธ์
0123456789abcdefABCDEF
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
การจัดรูปแบบสตริง (String Formatting)
คลาสสตริงที่สร้าง込ใน Python รองรับการแทนที่ตัวแปรและจัดรูปแบบค่าซับซ้อนผ่านเมธอด format()
รูปแบบพื้นฐาน:
'{} {}'.format(a, b)
ค่าของ a และ b จะถูกวางแทนที่ตำแหน่ง {} สามารถระบุตำแหน่ง (positional) หรือชื่อตัวแปรภายในวงเล็บได้
การเพิ่ม Padding
ไวยากรณ์: '{: (character) > (width)}'.format('string')
character: อักขระที่ใช้เติมwidth: ความกว้างทั้งหมด>: ชิดขวา,<: ชิดซ้าย,^: จัดกึ่งกลาง
การตัดสตริง (Truncate)
ไวยากรณ์: '{:.length}'.format('string') — ตัดให้เหลือจำนวนตัวอักษรที่กำหนด
ตัวอย่างการจัดรูปแบบ
print('The Name is {} and Roll {}'.format('Jhon', 40))
print('The values are {2}, {1}, {3}, {0}'.format(50, 70, 30, 15))
print('Value 1: {val1}, value 2: {val2}'.format(val2=20, val1=10))
print('{: >{width}}'.format('Hello', width=20))
print('{:_^{width}}'.format('Hello', width=20))
print('{:.5}'.format('Python Programming'))
ผลลัพธ์
The Name is Jhon and Roll 40
The values are 30, 70, 15, 50
Value 1: 10, value 2: 20
Hello
_______Hello________
Pytho
String Template
Template string ใช้สำหรับการแทนที่แบบง่ายขึ้น โดยใช้สัญลักษณ์ $ นำหน้าชื่อตัวระบุ
ไวยากรณ์:
myStr = string.Template("$a will be replaced")
myStr.substitute(a='XYZ')
สามารถใช้ dictionary ในการแทนที่ได้เช่นกัน
ตัวอย่าง Template
my_template = string.Template("The value of A is $X and Value of B is $Y")
my_str = my_template.substitute(X='Python', Y='Programming')
print(my_str)
my_dict = {'key1': 144, 'key2': 169}
my_template2 = string.Template("The first one $key1 and second one $key2")
my_str2 = my_template2.substitute(my_dict)
print(my_str2)
ผลลัพธ์
The value of A is Python and Value of B is Programming The first one 144 and second one 169