- Python中String模块详解
- 一、 字符串常量
- 二、 类
- 1、 格式化
- 1.1 介绍
- 1.2 简单应用
- 1.3 格式化输出
- 2、 模板化
- 1、 格式化
- 三、 函数
Python中String模块详解
一、 字符串常量
String库中的内置的所有常量:
源码中的概括:
whitespace -- a string containing all ASCII whitespaceascii_lowercase -- a string containing all ASCII lowercase lettersascii_uppercase -- a string containing all ASCII uppercase lettersascii_letters -- a string containing all ASCII lettersdigits -- a string containing all ASCII decimal digitshexdigits -- a string containing all ASCII hexadecimal digitsoctdigits -- a string containing all ASCII octal digitspunctuation -- a string containing all ASCII punctuation charactersprintable -- a string containing all ASCII characters considered printable
示例:
(相关资料图)
# -*- coding: utf-8 -*-"""Created on Sun Dec 18 18:58:35 2022@author: Steve Anthony"""import stringprint(string.whitespace) # 包含所有的空格print(string.ascii_lowercase) # 包含所有的小写字母print(string.ascii_uppercase) # 包含所有的大写字母print(string.ascii_letters) # 包含ASCII中的所有字母print(string.digits) # 包含所有的数字字符串print(string.hexdigits) # 包含所有的十六进制字符字符串print(string.octdigits) # 包含所有的八进制字符字符串print(string.punctuation) # 包含所有的标点符号字符串print(string.printable) # 包含所有可打印的ASCII字符字符串
二、 类
1、 格式化
1.1 介绍
String
模块中,有一个Formatter
类,其可以对字符串进行格式化。
该类中有一个format()
方法,和str.format()
方法使用方式类似,同时该类的主要作用就是使用format()
方法,对字符串进行格式化输出。
1.2 简单应用
print("{0}, {1}, {2}".format("a", "b", "c"))print("{}, {}, {}".format("a", "b", "c")) # 3.1+ onlyprint("{2}, {1}, {0}".format("a", "b", "c")) print("Coordinates: {latitude}, {longitude}".format(latitude="37.24N", longitude="-115.81W"))
同时,也可以结合元组或者字典的解包来使用。
1.3 格式化输出
>>> "{:<30}".format("left aligned") # 向右对齐,保留30个字符,如果字符不够使用空格填充"left aligned ">>> "{:>30}".format("right aligned") # 向左对齐,保留30个字符,如果字符不够使用空格填充" right aligned">>> "{:^30}".format("centered") # 居中对齐,保留30个字符,如果字符不够使用空格填充" centered ">>> "{:*^30}".format("centered") # use "*" as a fill char"***********centered***********">>> "{:+f}; {:+f}".format(3.14, -3.14) # show it always"+3.140000; -3.140000">>> "{: f}; {: f}".format(3.14, -3.14) # show a space for positive numbers" 3.140000; -3.140000">>> "{:-f}; {:-f}".format(3.14, -3.14) # show only the minus -- same as "{:f}; {:f}""3.140000; -3.140000">>> # format also supports binary numbers>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)"int: 42; hex: 2a; oct: 52; bin: 101010">>> # with 0x, 0o, or 0b as prefix:>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)"int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010">>> "Correct answers: {:.2%}".format(19/22) # 保留两位小数"Correct answers: 86.36%"
还可以用于对时间等特殊字符串的格式化
import datetimed = datetime.datetime(2010, 7, 4, 12, 15, 58)print("{:%Y-%m-%d %H:%M:%S}".format(d))
2、 模板化
模板字符串提供了更简单的字符串替换。因为在该上下文中,更简单的语法和功能使其比 Python 中的其他内置字符串格式设施更容易翻译。
模板字符串支持基于$
的替换,使用以下规则:
- 使用
$$
进行转义,其代表$
本身 $Identity
命名一个替换占位符,该占位符与映射关键字“Identity
”匹配。默认情况下,“标识符”仅限于以下划线或 ASCII 字母开头的任何不区分大小写的 ASCII 字母数字字符串(包括下划线)。$字符之后的第一个非标识符字符终止此占位符规范${identifier}
等价于$identifier
使用示例:
# -*- coding: utf-8 -*-"""Created on Sun Dec 18 18:58:35 2022@author: Steve Anthony"""from string import Templates = Template("$who的年龄为:${age}")print(s.safe_substitute({"who": "李华", "age": 13})) # safe_*这个函数如果没有给字符串里面的所有变量赋值不会报错print(s.safe_substitute(**{"who": "李华"}))print(s.substitute(**{"who": "李华", "age": 13})) # 但是这个函数,必须要给字符串里面所有定义的变量都赋值,否则会报错print(s.substitute({"who": "李华"}))
三、 函数
对于String
的常用方法,可以去Python基础语法里面学习
同时,有一个比较特殊的函数capwords(s, sep=" ")
,可以学习学习
作用,根据分隔符,将字符串分成几块,并且将每一块字符串的第一个字母转换为大写字母(如果不是字符则不改变),其余字母转换为小写字母,最后使用分隔符拼接回去。
使用示例:
# -*- coding: utf-8 -*-"""Created on Sun Dec 18 18:58:35 2022@author: Steve Anthony"""import stringa = string.capwords("*hello python! my nAmE iS")print(a)