如何创建带占位符的任意元素数量的Python字符串
我可以这样做:
string="%s"*3
print string %(var1,var2,var3)
但是我无法把这些变量放到另一个变量里,这样我就可以根据应用逻辑动态创建一个变量列表。例如:
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 中做到这一点?
3 个回答
1
n = 0
if condition:
increment n
vars.append(newvar)
else:
decrement n
vars.pop()
string = "%s" * n
print string with placeholders
不过,如果你只是想把变量连接在一起,其实不需要使用字符串格式化;为什么不这样做呢:
"".join( map( str, vars ) )
3
使用一个列表来添加或删除字符串,然后在打印之前用 "".join(yourlist) 把它们连接起来。
>>> q = []
>>> for x in range(3):
q.append("%s")
>>> "".join(q)
'%s%s%s'
>>> print "".join(q) % ("a","b","c")
abc
6
这样怎么样?
print ("%s" * len(vars)) % tuple(vars)
说真的,这样做有点傻。如果你只是想把所有的变量合成一个大字符串,这样做可能更好:
print ''.join(str(x) for x in vars)
不过,这个方法至少需要Python 2.4才能运行。