python字典的格式化字符串 分类: python 20130529 15:36 262人阅读 评论(0) 收藏

  字典的格式化字符串很酷。在每个转换说明符中的%字符后面,可以加上(用园括号括起来的)键不带引号。后面在跟上其他说明元素。

In [1]: phonebook = {'Alice':123, 'hello':456, 'sky':789}

In [2]: "Alice's phone number is %(Alice)s" % phonebook
Out[2]: "Alice's phone number is 123"

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

复制代码
In [4]: template = '''<html>
   ...: <head><title>%(title)s</title></head>
   ...: <body>
   ...: <h1>%(title)s</h1>
   ...: <p>%(text)s</p>
   ...: </body>'''

In [5]: data = {'title':'My Home Page', 'text':'Welcome to my home page!'}

In [6]: print template % data
<html>
<head><title>My Home Page</title></head>
<body>
<h1>My Home Page</h1>
<p>Welcome to my home page!</p>
</body>
复制代码
原文地址:https://www.cnblogs.com/think1988/p/4628177.html