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.
相关推荐
张琪杭6 分钟前
pytorch tensor创建tensor
人工智能·pytorch·python
星星点点洲16 分钟前
【RAG】RAG 系统的基本搭建流程(ES关键词检索示例)
python·elasticsearch
带娃的IT创业者38 分钟前
《Python实战进阶》No18: 使用 Apache Spark 进行分布式计算
python·spark·apache
Tomorrow'sThinker1 小时前
Python零基础学习第三天:函数与数据结构
开发语言·windows·python
元媛媛1 小时前
Python - 轻量级后端框架 Flask
开发语言·python·flask
疏狂难除1 小时前
基于Rye的Django项目通过Pyinstaller用Github工作流简单打包
后端·python·django
囚~徒~1 小时前
flask 接口文档自动化
python·flask·自动化
行码棋2 小时前
【Python】omegaconf 用法详解
开发语言·python
SomeB1oody2 小时前
【Python机器学习】1.6. 逻辑回归理论(基础):逻辑函数、逻辑回归的原理、分类任务基本框架、通过线性回归求解分类问题
人工智能·python·机器学习·分类·逻辑回归·线性回归
朝丽雨月2 小时前
Manus智能体多代理协同系统:架构创新与实践应用
人工智能·python