Python内置模块-String
一、模块介绍
String
模块是Python
的内置模块,提供了各种操作字符串的工具和函数。
二、模块导入
import string
三、字符串常量
ascii_letters
:所有小写和大写ASCII
字母ascii_lowercase
:所有小写ASCII
字母ascii_uppercase
:所有大写ASCII
字母digits
:所有的十进制数字hexdigits
:所有的十六进制数字octdigits
:所有的八进制数字printable
:所有的可打印字符punctuation
:所有的标点字符whitespace
:所有的空白字符
常量使用
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
print(string.octdigits)
print(string.printable)
print(string.punctuation)
print(string.whitespace)
结果
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
01234567
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
四、函数
1.string.capwords()
作用 将输入字符串按照单词边界进行分割,并将每个单词的首字母转换为大写,其余字母转换为小写。
语法
string.capwords(s, sep=None)
参数
s
:要处理的字符串sep
:可用于指定单词之间的分隔符,默认情况下,capwords
使用空格作为分隔符
示例
- 基本使用
import string
# 基本使用,将每个单词的首字母大写
s = "hello world"
print(string.capwords(s)) # 输出: Hello World
- 指定分隔符
import string
# 指定分隔符为逗号
s = "hello,world,this,is,a,test"
print(string.capwords(s, sep=',')) # 输出: Hello,World,This,Is,A,Test
- 处理混合大小写的字符串
import string
# 处理混合大小写的字符串
s = "HELLO world, tHIS iS a TeST"
print(string.capwords(s)) # 输出: Hello World, This Is A Test
五、字符串模板
string.Template
类提供了一个简单的方法来替换字符串中的特定标记,在使用格式化字符串时很有用。
from string import Template
# 创建一个模板
tmpl = Template("Hello, $name!$greeting")
# 使用字典进行替换
print(tmpl.substitute(name="张三", greeting="祝你今天愉快"))
# 使用关键字参数进行替换
print(tmpl.substitute(name="李四", greeting="你好吗?"))
结果
Hello, 张三!祝你今天愉快
Hello, 李四!你好吗?