Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Common String Operations ใน Python (โมดูล string)

โมดูล string ใน Standard Library ของ Python มี Constants, Classes และ Helper Function capwords() ที่มีประโยชน์

Constants

Constantคำอธิบาย
ascii_lettersรวม lowercase และ uppercase
ascii_lowercaseตัวอักษรพิมพ์เล็ก 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercaseตัวอักษรพิมพ์ใหญ่ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digitsตัวเลข '0123456789'
hexdigitsHexadecimal '0123456789abcdefABCDEF'
octdigitsOctal '01234567'
punctuationอักขระ Punctuation ใน ASCII
printableอักขระที่พิมพ์ได้ทั้งหมด
whitespaceWhitespace characters: space, tab, linefeed, return, formfeed, vertical tab

ฟังก์ชัน capwords()

ทำงาน 3 ขั้นตอน:

  1. แยกสตริงเป็นคำด้วย str.split()
  2. ทำนำหน้าตัวใหญ่แต่ละคำด้วย str.capitalize()
  3. รวมคำกลับด้วย 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'