Python中的输出格式:用相同的变量替换几个%s

时间:2011-08-08 13:36:50

标签: string-formatting python

我正在尝试维护/更新/重写/修复一些看起来有点像这样的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)

整个脚本中都有一些看起来像这样的片段,我想知道是否有更简单(更Pythonic?)的方式来编写这段代码。我找到了一个这样的实例,它替换了相同的变量大约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 个答案:

答案 0 :(得分:56)

改为使用字典。

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')

答案 1 :(得分:6)

使用格式化字符串:

>>> 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'
>>>

答案 2 :(得分:5)

使用新的string.format

name = 'Alex'
variable = """My name is {0} and it has been {0} since I was born.
          My parents decided to call me {0} because they thought {0} was a nice name.
          {0} is the same as {0}.""".format(name)

答案 3 :(得分:5)

>>> "%(name)s %(name)s hello!" % dict(name='foo')
'foo foo hello!'

答案 4 :(得分:3)

您可以使用命名参数。 See examples here

答案 5 :(得分:2)

variable = """My name is {0} and it has been {0} since I was born.
              My parents decided to call me {0} because they thought {0} was a nice name.
              {0} is the same as {0}.""".format(name)

答案 6 :(得分:1)

答案 7 :(得分:0)

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.

答案 8 :(得分:0)

如果您使用的是Python 3,那么您还可以利用f字符串

myname = "Test"
sample_string = "Hi my name is {name}".format(name=myname)

sample_string = f"Hi my name is {myname}"