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

การดำเนินการกับสตริงใน Python


โมดูล string และค่าคงที่

ใน Python มีไลบรารีมาตรฐานชื่อ string ซึ่งประกอบด้วยค่าคงที่ เมธอด และคลาสต่างๆ ที่เกี่ยวข้องกับสตริง

เพื่อใช้งาน โมดูลนี้ต้องนำเข้า (import) ก่อน:

import string

ค่าคงที่สำคัญและค่าที่เก็บอยู่:

ลำดับค่าคงที่และค่า
1string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
2string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
3string.ascii_letters
การรวม ascii_lowercase และ ascii_uppercase: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
4string.digits
'0123456789'
5string.hexdigits
'0123456789abcdefABCDEF'
6string.octdigits
'01234567'
7string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
8string.printable
อักขระ ASCII ที่พิมพ์ได้ทั้งหมด รวมตัวอักษร สัญลักษณ์ ตัวเลข และ whitespace
9string.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