Python字符串模塊

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

Python 字符串模块

它是一个内置模块,在使用任何常量和类之前我们必须先导入它。

字符串模块常量

让我们来看看字符串模块中定义的常量。

import string

# 字符串模块常量
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或为None,则会删除前导和尾随空格,并使用单个空格分隔单词。如果提供了分隔符,则使用该分隔符来分割和连接单词。

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

输出:Welcome To Journaldev

Python 字符串模块类

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

Formatter

它的行为与str.format()函数完全相同。如果您想要对其进行子类化并定义自己的格式字符串语法,则该类非常有用。让我们看一个使用Formatter类的简单示例。

from string import Formatter

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

# format() 行為類似
print('{} {website}'.format('Welcome to', website='JournalDev'))

輸出:

Welcome to JournalDev
Welcome to JournalDev

模板

這個類別用於建立簡單字串替換的字串模板,如PEP 292所描述。在應用程式中實現國際化(i18n)時很有用,其中我們不需要複雜的格式化規則。

from string import Template

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

輸出: Pankaj 是 JournalDev 的創始人。

您可以從我們的GitHub Repository查看完整的 Python 腳本和更多 Python 範例。

參考:官方文檔

Source:
https://www.digitalocean.com/community/tutorials/python-string-module