我可以
string="%s"*3
print string %(var1,var2,var3)
但我无法将 vars 放入另一个变量中,因此我可以使用应用程序逻辑动态创建 vars 列表。 例如
if condition:
add a new %s to string variable
vars.append(newvar)
else:
remove one %s from string
vars.pop()
print string with placeholders
关于如何使用 python 2.6 执行此操作的任何想法?
最佳答案
这个怎么样?
print ("%s" * len(vars)) % tuple(vars)
但实际上,这是一种相当愚蠢的做事方式。如果您只想将所有变量压缩到一个大字符串中,这可能是一个更好的主意:
print ''.join(str(x) for x in vars)
至少需要 Python 2.4 才能工作。
关于python - 如何使用具有任意数量元素的占位符创建 python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3468916/