0

4.2.3Python下字典的格式化字符串

Posted by 撒得一地 on 2016年2月14日 in python教程

可以使用字符串格式化功能来格式化元组中的所有值,同样也可以使用字典来完成同样的工作。字典是通过格式化键名,进而得到相对应的值。

字典格式化字符串操作是通过在每个转换说明符(conversion specifier)中的%字符后面,然后添加上(用圆括号括起来)键名,后面再跟上其他说明元素。比如:

>>> phonebook = {'psz':'0592111','peter':'0591111'}
>>> "psz's phone number is %(psz)s." % phonebook
"psz's phone number is 0592111."

从上面可以看到,在被格式化的字符串后面,要加上%和所包含键名的字典。

除了增加的字符串键之外,转换说明符还是像以前一样工作。当以这种方式使用字典的时候,只要所给出的键都能在字典中找到,就可以获得任意数量的转换说明符。这类字符串格式化在模板系统中非常有用。比如:

>>> template = '''<html>
... <head><title>%(title)s</title></head>
... <body>
... <h1>%(title)s</h1>
... <p>%(text)s</p>
... </body>
... </head>
... </html>'''
>>> data = {'title':'Test page','text':'welcome'}
>>> print(template % data)
<html>
<head><title>Test page</title></head>
<body>
<h1>Test page</h1>
<p>welcome</p>
</body>
</head>
</html>

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

8 + 4 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.