2011-08-08 20 views
15

我正在嘗試維護/更新/重寫/修復一些看起來有點像這樣的Python:Python中的輸出格式:用相同的變量替換幾個%s

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) 

回答

47

使用字典來代替。

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

您的最後一個選項非常精美,非常感謝 - 正是我對Python的期望! – alexmuller

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) 
5
>>> "%(name)s %(name)s hello!" % dict(name='foo') 
'foo foo hello!' 
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) 
3

使用格式的字符串:

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