Python 标准库:string——字符串操作

文章目录

  • 模块介绍
  • 主要常量
  • 主要类
    • [- Formatter](#- Formatter)
    • [- Template](#- Template)
  • 主要函数
    • [- capwords()](#- capwords())
    • [- Template.substitute()](#- Template.substitute())
    • [- Formatter.format()](#- Formatter.format())

模块介绍

string 模块提供了许多与字符串操作相关的常量和函数。它主要用于处理字符串,包括字符集合、格式化操作和其他与字符串相关的功能。

主要常量

常量 描述
string.ascii_letters 包含所有的 ASCII 字母(包括大写和小写字母): abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_lowercase 包含所有的小写字母: abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase 包含所有的大写字母: ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits 包含所有的十进制数字字符: 0123456789
string.punctuation 包含所有的标点符号字符: !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
string.whitespace 包含所有的空白字符: \t\n\r\v\f
string.printable 包含所有可以打印的字符,包括数字、字母、标点符号和空白字符: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ \t\n\r\v\f

主要类

描述
Template 提供基于 $ 占位符的字符串模板替换功能,适用于简单的字符串格式化。
Formatter 提供基于 {} 占位符的字符串格式化功能,支持更复杂的格式化操作,常用于高级格式化需求。

- Formatter

string.Formatter 是 Python 格式化字符串的一个高级工具,用于通过花括号 {} 占位符进行格式化。

尽管 Python 的 f-string 和 str.format() 已经成为最常用的格式化方式,但 string.Formatter 仍然有其独特的用途。

- Template

提供基于 $ 占位符的字符串模板替换功能,适用于简单的字符串格式化,它比 str.format() 更简洁和易于使用。

主要函数

函数 描述
capwords() 将字符串中的每个单词的首字母大写,其余字母小写,并以空格分隔。
Template.substitute() 通过 $ 占位符进行字符串替换,提供更简便的模板替换功能。
Formatter.format() 使用花括号 {} 占位符,进行字符串格式化替换。

- capwords()

将字符串中的每个单词的首字母大写,其他字母小写。

python 复制代码
import string

# 将字符串中的每个单词的首字母大写
text = "hello world, this is python!"
capitalized_text = string.capwords(text)
print(capitalized_text)

输出:

python 复制代码
Hello World, This Is Python!

- Template.substitute()

通过 $ 占位符进行字符串替换,提供更简便的模板替换功能。

python 复制代码
import string

# 创建一个 Template 对象
template = string.Template("Hello $name, you are $age years old.")

# 使用 substitute 方法进行字符串替换
result = template.substitute(name="Alice", age=30)
print(result)

输出:

python 复制代码
Hello Alice, you are 30 years old.

- Formatter.format()

使用花括号 {} 占位符,进行字符串格式化替换。

python 复制代码
import string

# 创建一个 Formatter 对象
formatter = string.Formatter()

# 格式化字符串
formatted_string = formatter.format("Hello {name}, you are {age} years old.", name="Alice", age=30)
print(formatted_string)

输出:

python 复制代码
Hello Alice, you are 30 years old.
相关推荐
c8i1 小时前
django中的FBV 和 CBV
python·django
c8i1 小时前
python中的闭包和装饰器
python
这里有鱼汤4 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩14 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在19 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP21 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python