当前位置:首页 » 《随便一记》 » 正文

Python 字符串模块

8 人参与  2024年03月06日 18:26  分类 : 《随便一记》  评论

点击全文阅读


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)

输出:

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

string capwords() 函数

Python字符串模块包含一个实用函数 - capwords(s, sep=None)。此函数使用str.split()将指定的字符串拆分为单词。然后,它使用str.capitalize()函数对每个单词进行大写处理。最后,它使用str.join()连接大写单词。如果未提供可选参数sep或为None,则会删除前导和尾随空格,并使用单个空格分隔单词。如果提供了sep,则使用该分隔符拆分和连接单词。

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

输出:Welcome To Journaldev

Python字符串模块类

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

Formatter

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

from string import Formatterformatter = 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 JournalDevWelcome to JournalDev

Template

此类用于创建字符串模板,以便进行更简单的字符串替换,如PEP 292中所述。在实现国际化(i18n)的应用程序中,它对于不需要复杂格式规则的情况非常有用。

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

输出:Pankaj is the Founder of JournalDev.


点击全文阅读


本文链接:http://zhangshiyu.com/post/74978.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1