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.
相关推荐
程序员三藏15 分钟前
Selenium+python自动化测试:解决无法启动IE浏览器及报错问题
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
瓦尔登湖50830 分钟前
DAY 40 训练和测试的规范写法
python
站大爷IP1 小时前
Python中None与NoneType的真相:从单例对象到类型系统的深度解析
python
秋难降1 小时前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法
站大爷IP1 小时前
Python新手踩坑实录:这些错误你可能正在犯
python
我星期八休息1 小时前
大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
大数据·人工智能·python
深盾安全1 小时前
uv,下一代Python包管理工具
python
山烛2 小时前
OpenCV 图像处理基础操作指南(二)
人工智能·python·opencv·计算机视觉
跟橙姐学代码2 小时前
学Python,先把这“三板斧”练到炉火纯青!(零基础也能看懂)
前端·python
让心淡泊1443 小时前
DAY 50 预训练模型+CBAM模块
python