[雪峰磁针石博客]python标准模块介绍-string:文本常量和模板
string—文本常量和模板
作用:包含处理文本的常量和类。
Python版本:1.4及以后版本
最早的Python版本就有string模块。 之前在这个模块中实现的许多函数已经移至str对象的方法。 string模块保留了几个有用的常量和类,用于处理str对象。
函数
capwords()的将字符串中所有单词的首字母大写。
#!python
>>> import string
>>> t = "hello world!"
>>> string.capwords(t)
'Hello World!'
>>> t
'hello world!'
>>> t.capitalize()
'Hello world!'
>>> t
'hello world!'
结果等同于先调用split(),把结果列表中各个单词的首字母大写,然后调用join()合并结果。
因为str对象已经有capitalize()方法,该函数的实际意义并不大。
模板
字符串模板已经作为PEP 292的一部分增加到Python 2.4中,并得到扩展,以替代内置拼接(interpolation)语法类似。使用string.Template拼接时,可以在变量名前面加上前缀$(如$var)来标识变量,如果需要与两侧的文本相区分,还可以用大括号将变量括起(如${var})。
下面的例子对简单的模板和使用%操作符及str.format()进行了比较。
#!python
import string
values = {'var': 'foo'}
t = string.Template("""
Variable : $var
Escape : $$
Variable in text: ${var}iable
""")
print('TEMPLATE:', t.substitute(values))
s = """
Variable : %(var)s
Escape : %%
Variable in text: %(var)siable
"""
print('INTERPOLATION:', s % values)
s = """
Variable : {var}
Escape : {{}}
Variable in text: {var}iable
"""
print('FORMAT:', s.format(**values))
"""
print 'INTERPOLATION:', s % values
执行结果:
#!python
python3 string_template.py
TEMPLATE:
Variable : foo
Escape : $
Variable in text: fooiable
INTERPOLATION:
Variable : foo
Escape : %
Variable in text: fooiable
FORMAT:
Variable : foo
Escape : {}
Variable in text: fooiable
模板与标准字符串拼接的重要区别是模板不考虑参数类型。模板中值会转换为字符串且没有提供格式化选项。例如没有办法控制使用几位有效数字来表示浮点数值。
通过使用safe_substitute()方法,可以避免未能提供模板所需全部参数值时可能产生的异常。
tring_template_missing.py
#!python
import string
values = {'var': 'foo'}
t = string.Template("$var is here but $missing is not provided")
try:
print('substitute() :', t.substitute(values))
except KeyError as err:
print('ERROR:', str(err))
print('safe_substitute():', t.safe_substitute(values))
由于values字典中没有对应missing的值,因此substitute()会产生KeyError。不过,safe_substitute()不会抛出这个错误,它将捕获这个异常,并在文本中保留变量表达式。
#!python
$ python3 string_template_missing.py
ERROR: 'missing'
safe_substitute(): foo is here but $missing is not provided
高级模板(非常用)
可以修改string.Template的默认语法,为此要调整它在模板体中查找变量名所使用的正则表达式模式。简单的做法是修改delimiter和idpattern类属性。
string_template_advanced.py
#!python
import string
class MyTemplate(string.Template):
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
template_text = '''
Delimiter : %%
Replaced : %with_underscore
Ignored : %notunderscored
'''
d = {
'with_underscore': 'replaced',
'notunderscored': 'not replaced',
}
t = MyTemplate(template_text)
print('Modified ID pattern:')
print(t.safe_substitute(d))
执行结果:
#!python
$ python3 string_template_advanced.py
Modified ID pattern:
Delimiter : %
Replaced : replaced
Ignored : %notunderscored
默认模式
#!python
>>> import string
>>> t = string.Template('$var')
>>> print(t.pattern.pattern)
\$(?:
(?P<escaped>\$) | # Escape sequence of two delimiters
(?P<named>(?-i:[_a-zA-Z][_a-zA-Z0-9]*)) | # delimiter and a Python identifier
{(?P<braced>(?-i:[_a-zA-Z][_a-zA-Z0-9]*))} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
string_template_newsyntax.py
#!python
import re
import string
class MyTemplate(string.Template):
delimiter = '{{'
pattern = r'''
\{\{(?:
(?P<escaped>\{\{)|
(?P<named>[_a-z][_a-z0-9]*)\}\}|
(?P<braced>[_a-z][_a-z0-9]*)\}\}|
(?P<invalid>)
)
'''
t = MyTemplate('''
{{{{
{{var}}
''')
print('MATCHES:', t.pattern.findall(t.template))
print('SUBSTITUTED:', t.safe_substitute(var='replacement'))
执行结果:
#!python
$ python3 string_template_newsyntax.py
MATCHES: [('{{', '', '', ''), ('', 'var', '', '')]
SUBSTITUTED:
{{
replacement
格式化
Formatter类实现与str.format()类似。 其功能包括类型转换,对齐,属性和字段引用,命名和位置模板参数以及特定类型的格式选项。 大多数情况下,fformat()方法是这些功能的更方便的接口,但是Formatter是作为父类,用于需要变化的情况。
常量
string模块包含许多与ASCII和数字字符集有关的常量。
string_constants.py
#!python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入)
# qq群:144081101 591302926 567351477
# CreateDate: 2018-6-12
import inspect
import string
def is_str(value):
return isinstance(value, str)
for name, value in inspect.getmembers(string, is_str):
if name.startswith('_'):
continue
print('%s=%r\n' % (name, value))
执行结果
#!python
$ python3 string_constants.py
ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase='abcdefghijklmnopqrstuvwxyz'
ascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits='0123456789'
hexdigits='0123456789abcdefABCDEF'
octdigits='01234567'
printable='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
whitespace=' \t\n\r\x0b\x0c'
参考资料
- 本文最新版本地址
- 本文涉及的python测试开发库 谢谢点赞!
- 本文相关海量书籍下载
- 讨论 钉钉免费群21745728 qq群144081101 567351477
- Standard library documentation for string
- String Methods – Methods of
str
objects that replace the deprecated functions instring
. - PEP 292 – Simpler String Substitutions
- Format String Syntax – The formal definition of the layout specification language used by
Formatter
andstr.format()
.

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
C# 应用Excel条件格式(一)
Excel中的条件格式功能是个十分强大且方便的功能,通过对使用条件格式功能可以在很大程度上改进表格的设计和可读性,用户可以指定单个或者多个单元格区域应用一种或者多种格式,如此一来,也在大大提高了表格的可操作性。下面将介绍在C#编程中如何来设置并应用Excel条件格式。 示例要点概述: 1. 基于单元格值应用条件格式 2. 基于自定义公式应用条件格式 3. 应用数据条条件类型格式 4. 删除条件格式 4.1 删除指定数据范围中的条件格式 4.2 删除全部条件格式 使用工具 Free Spire.XLS for .NET 8.3(免费版) Visual Studio 示例代码(供参考) 测试文档如下: 【示例 1 】应用条件格式 using Spire.Xls; using System.Drawing; namespace ConditionalFormatting_XLS { class Program { static void Main(string[] args) { //实例化workbook对象并加载文档 Workbook wb = new Workbook(); wb...
-
下一篇
服务化改造实践(一)| Dubbo + ZooKeeper
“没有最好的技术,只有最合适的技术。”我想这句话也同样适用于微服务领域,没有最好的服务框架,只有最适合自己的服务改造。在 Dubbo 的未来规划中,除了保持自身技术上的领先性,关注性能、大流量、大规模集群领域的挑战外,围绕 Dubbo 核心来发展生态,将 Dubbo 打造成一个服务化改造的整体方案也是重点之一。从本期开始,我们将推出“服务化改造”系列文章,通过在一些外围系统和服务化基础组件上的开发实践,分享Dubbo 生态下的服务化改造收获和总结。 » 8月26日,Aliware Open Source 将首次在成都举办 Apache Dubbo 的meetup活动,Dubbo 、Sentinel和 Nacos 的小哥哥和小姐姐都会在现场进行技术分享,欢迎成都的朋友报名参加我们的活动喔,搜索“阿里巴巴中间件”公众号,后台发送“成都m
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- SpringBoot2整合Redis,开启缓存,提高访问速度
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Dcoker安装(在线仓库),最新的服务器搭配容器使用
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- SpringBoot2全家桶,快速入门学习开发网站教程
- CentOS7,8上快速安装Gitea,搭建Git服务器