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.
相关推荐
成功人chen某1 小时前
配置VScodePython环境Python was not found;
开发语言·python
2301_786964362 小时前
EXCEL Python 实现绘制柱状线型组合图和树状图(包含数据透视表)
python·microsoft·excel
skd89992 小时前
小蜗牛拨号助手用户使用手册
python
「QT(C++)开发工程师」2 小时前
STM32 | FreeRTOS 递归信号量
python·stm32·嵌入式硬件
史迪仔01122 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
胡耀超3 小时前
18.自动化生成知识图谱的多维度质量评估方法论
人工智能·python·自动化·知识图谱·数据科学·逻辑学·质量评估
三块钱07943 小时前
【原创】基于视觉大模型gemma-3-4b实现短视频自动识别内容并生成解说文案
开发语言·python·音视频
神码小Z3 小时前
Ubuntu快速安装Python3.11及多版本管理
python
JOYUAGV3 小时前
Word压缩解决方案
python·word
mahuifa4 小时前
(9)python开发经验
python·开发经验