我正在尝试维护/更新/重写/修复一点类似以下的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)
用字典代替。
或者
format
使用显式编号。或者
format
使用命名参数。使用新的
string.format
:使用格式字符串:
{}中的文本可以是描述符或索引值。
另一个奇特的技巧是使用字典结合**运算符定义多个变量。
相关问题 更多 >
编程相关推荐