โมดูล string ใน Standard Library ของ Python มี Constants, Classes และ Helper Function capwords() ที่มีประโยชน์
Constants
| Constant | คำอธิบาย |
|---|---|
ascii_letters | รวม lowercase และ uppercase |
ascii_lowercase | ตัวอักษรพิมพ์เล็ก 'abcdefghijklmnopqrstuvwxyz' |
ascii_uppercase | ตัวอักษรพิมพ์ใหญ่ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
digits | ตัวเลข '0123456789' |
hexdigits | Hexadecimal '0123456789abcdefABCDEF' |
octdigits | Octal '01234567' |
punctuation | อักขระ Punctuation ใน ASCII |
printable | อักขระที่พิมพ์ได้ทั้งหมด |
whitespace | Whitespace characters: space, tab, linefeed, return, formfeed, vertical tab |
ฟังก์ชัน capwords()
ทำงาน 3 ขั้นตอน:
- แยกสตริงเป็นคำด้วย
str.split() - ทำนำหน้าตัวใหญ่แต่ละคำด้วย
str.capitalize() - รวมคำกลับด้วย
str.join()
ตัวอย่าง
>>> import string >>> text = 'All animals are equal. Some are more equal' >>> string.capwords(text) 'All Animals Are Equal. Some Are More Equal'
Formatter Class
คลาสสำหรับ Format String แบบกำหนดเอง สามารถสืบทอด (subclass) เพื่อเขียน Custom Formatter
>>> from string import Formatter
>>> f = Formatter()
>>> f.format('name:{name}, age:{age}, marks:{marks}', name='Rahul', age=30, marks=50)
'name:Rahul, age:30, marks:50'
Template Class
ใช้สร้าง String Template เหมาะสำหรับการแทนที่ค่าประเภทง่ายๆ
>>> from string import Template >>> text = 'My name is $name. I am $age years old' >>> t = Template(text) >>> t.substitute(name='Rahul', age=30) 'My name is Rahul. I am 30 years old'