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_letters | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ |
ascii_lowercase | abcdefghijklmnopqrstuvwxyz |
ascii_uppercase | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
digits | 0123456789 |
hexdigits | 0123456789abcdefABCDEF |
octdigits | 01234567 |
punctuation | !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ |
printable | digits + ascii_letters + punctuation + whitespace |
whitespace | space, 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ức | Mô 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-string | Formatted 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}')