Python字符串模块

时间:2020-02-23 14:43:29  来源:igfitidea点击:

Python String模块包含一些常量,实用程序函数和用于字符串操作的类。

Python字符串模块

这是一个内置模块,我们必须先导入它,然后才能使用其任何常量和类。

字符串模块常量

让我们看一下string模块中定义的常量。

import string

# string module constants
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
print(string.whitespace)  # ' \t\n\r\x0b\x0c'
print(string.punctuation)

输出:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
 	

!"#$%&'()*+,-./:;?@[\]^_"{|}~

字符串capwords()函数

Python字符串模块包含一个实用程序函数– capwords(s,sep = None)。
此函数使用str.split()将指定的字符串拆分为单词。
然后使用str.capitalize()函数将每个单词大写。
最后,它使用str.join()连接大写单词。

如果未提供可选参数sep或者"无",则将删除前导和尾随空格,并用单个空格分隔单词。
如果提供了分隔符,则使用分隔符分隔和连接单词。

s = '  Welcome TO  \n\n theitroad '
print(string.capwords(s))

输出:Welcome to theitroad

Python字符串模块类

Python字符串模块包含两个类-Formatter和Template。

格式化程序

它的行为与str.format()函数完全相同。
如果您想对其进行子类化并定义自己的格式字符串语法,该类将非常有用。

让我们看一个使用Formatter类的简单示例。

from string import Formatter

formatter = Formatter()
print(formatter.format('{website}', website='theitroad'))
print(formatter.format('{} {website}', 'Welcome to', website='theitroad'))

# format() behaves in similar manner
print('{} {website}'.format('Welcome to', website='theitroad'))

输出:

Welcome to theitroad
Welcome to theitroad

模板

此类用于创建用于更简单的字符串替换的字符串模板(如PEP 292中所述)。
在不需要复杂格式规则的应用程序中实现国际化(i18n)很有用。

from string import Template

t = Template('$name is the $title of $company')
s = t.substitute(name='hyman', title='Founder', company='theitroad.')
print(s)