我正在嘗試維護/更新/重寫/修復一些看起來有點像這樣的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)
您的最後一個選項非常精美,非常感謝 - 正是我對Python的期望! – alexmuller