Python中的输出格式化:用相同变量替换多个%s
我正在尝试维护/更新/重写/修复一段看起来像这样的Python代码:
variable = """My name is %s and it has been %s since I was born.
My parents decided to call me %s because they thought %s was a nice name.
%s is the same as %s.""" % (name, name, name, name, name, name)
在这个脚本的各个地方都有类似的小片段,我在想是否有更简单(更符合Python风格?)的写法。我发现有一个地方的同一个变量被替换了大约30次,感觉实在太难看了。
我觉得唯一解决这种(在我看来)难看的方法就是把它拆分成很多小块吗?
variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)
9 个回答
10
使用格式化字符串:
>>> variable = """My name is {name} and it has been {name} since..."""
>>> n = "alex"
>>>
>>> variable.format(name=n)
'My name is alex and it has been alex since...'
大括号 {} 里面的内容可以是一个描述符或者一个索引值。
还有一个很酷的技巧是,可以用字典来定义多个变量,并结合 ** 操作符来使用。
>>> values = {"name": "alex", "color": "red"}
>>> """My name is {name} and my favorite color is {color}""".format(**values)
'My name is alex and my favorite color is red'
>>>
11
Python 3.6 引入了一种更简单的字符串格式化方法。你可以在 PEP 498 中找到详细信息。
>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'
它还支持在运行时进行评估。
>>>f"{2 * 30}"
'60'
它也支持字典操作。
>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
The comedian is Tom, aged 30.
82
用字典来代替吧。
var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }
或者用format
来明确指定数字。
var = '{0} {0} {0}'.format('look_at_meeee')
当然,也可以用format
来指定名字参数。
var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')