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

2024-05-14 22:36:36 发布

您现在位置: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)

脚本中到处都是这样的小片段,我想知道是否有一个更简单(更像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)

Tags: andtonameismyitcallvariable
3条回答

用字典代替。

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

使用新的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)

使用格式字符串:

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

相关问题 更多 >

    热门问题