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.
相关推荐
一只小波波呀37 分钟前
打卡第48天
python
zstar-_1 小时前
一套个人知识储备库构建方案
python
Amo Xiang1 小时前
《100天精通Python——基础篇 2025 第5天:巩固核心知识,选择题实战演练基础语法》
python·选择题·基础语法
江梦寻1 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing1 小时前
Python——MySQL远程控制
开发语言·python·mysql
miniwa1 小时前
Python编程精进:CSV 模块
python
老胖闲聊8 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1189 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之9 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao10 小时前
使用python实现奔跑的线条效果
python·绘图