Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Các thao tác chuỗi (string) phổ biến trong Python

Module string trong thư viện chuẩn cung cấp hằng số, lớp Formatter, Template và hàm capwords().

Hằng số (Constants)

Hằng sốGiá trị
ascii_lettersabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
ascii_lowercaseabcdefghijklmnopqrstuvwxyz
ascii_uppercaseABCDEFGHIJKLMNOPQRSTUVWXYZ
digits0123456789
hexdigits0123456789abcdefABCDEF
octdigits01234567
punctuation!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
printabledigits + ascii_letters + punctuation + whitespace
whitespacespace, tab, linefeed, return, formfeed, vertical tab

Hàm capwords()

Viết hoa chữ cái đầu mỗi từ:

import string
text = 'All animals are equal. Some are more equal'
print(string.capwords(text))
# 'All Animals Are Equal. Some Are More Equal'

Lớp Formatter

Tùy biến formatting nâng cao (subclass để custom).

from string import Formatter
f = Formatter()
result = f.format('name:{name}, age:{age}, marks:{marks}', name='Rahul', age=30, marks=50)
print(result)  # 'name:Rahul, age:30, marks:50'

Lớp Template (String substitution đơn giản)

Dùng $identifier hoặc ${identifier}:

from string import Template
text = 'My name is $name. I am $age years old'
t = Template(text)
print(t.substitute(name='Rahul', age=30))
# 'My name is Rahul. I am 30 years old' 

# safe_substitute: không báo lỗi nếu thiếu key
print(t.safe_substitute(name='Rahul'))  # 'My name is Rahul. I am $age years old'

Phương thức chuỗi built-in hữu ích

Phương thứcMô tả
str.split(sep=None)Tách chuỗi thành list
str.join(iterable)Nối list thành chuỗi
str.strip()Xóa whitespace đầu/cuối
str.replace(old, new)Thay thế substring
str.format()Format chuỗi (PEP 3101)
f-stringFormatted string literal (Python 3.6+)

Ví dụ f-string (khuyên dùng Python 3.6+)

name = "Rahul"
age = 30
print(f'Name: {name}, Age: {age}, Age*2: {age*2}')