什么是 string 模块?
Python 的 string 模块提供了一系列用于处理字符串的常量、类和函数。
虽然很多功能已被内置到 str 类型中,但该模块仍包含一些实用工具,
如字符串模板(Template)和标准字符集常量。
常用常量
以下是一些常用的字符串常量:
| 常量 | 说明 | 示例值 |
|---|---|---|
string.ascii_letters |
所有 ASCII 字母(大小写) | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ |
string.ascii_lowercase |
小写 ASCII 字母 | abcdefghijklmnopqrstuvwxyz |
string.ascii_uppercase |
大写 ASCII 字母 | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
string.digits |
数字字符 | 0123456789 |
string.punctuation |
标点符号 | !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ |
string.whitespace |
空白字符(空格、换行等) | \t\n\r\x0b\x0c |
示例:使用常量生成随机密码
import string
import random
chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choices(chars, k=12))
print(password) # 输出类似:K9#mN$pL2xQ!
字符串模板(Template)
string.Template 提供了一种安全的字符串替换方式,适用于用户输入不可信的场景。
使用 $ 符号标识占位符。
示例:使用 Template 进行变量替换
from string import Template
tmpl = Template('Hello, $name! You have $count messages.')
result = tmpl.substitute(name='Alice', count=5)
print(result) # 输出:Hello, Alice! You have 5 messages.
与 f-string 或 % 格式化不同,Template 在键缺失时会抛出异常,
但可通过 safe_substitute() 避免错误。
其他实用函数
string.capwords(s):将字符串中每个单词首字母大写。
示例:使用 capwords
import string
text = "hello world from python"
result = string.capwords(text)
print(result) # 输出:Hello World From Python