在Python中扩展列表中的变量
需要知道如何在列表元素中展开变量
>>> one_more = "four"
>>> var_names = ["one", "two", "three_<expand variable one_more>"]
应该得到类似这样的结果
['one', 'two', 'three_four']
2 个回答
0
我猜你是想在一个列表里替换字符串。这里有一个例子可以满足你的需求。
one_more = "four"
var_names = ["one", "two", "three_<var>"]
print [x.replace("<var>", one_more) for x in var_names]
>>> ["one", "two", "three_four"]
如果你想一次性替换多个模式,可以这样做:
a = "AA"
b = "BB"
var_names = ["one", "two", "three_$a", "four_$b"]
def batch_replace(str, lookup):
for pattern in lookup:
replacement = lookup[pattern]
str = str.replace(pattern, replacement)
return str
print [batch_replace(x, {"$a": a, "$b": b}) for x in var_names]
>>> ["one", "two", "three_AA", "four_BB"]
2
非常基础:
In [1]: a="four"
In [2]: b="five"
In [3]: ['one', 'two', 'three_%s' % a]
Out[3]: ['one', 'two', 'three_four']
你还可以把一组变量连接起来:
In [5]: ['one', 'two', 'three_%s' % '_'.join((a,b))]
Out[5]: ['one', 'two', 'three_four_five']
这里是用 str.format 的同样解决方案:
In [6]: ['one', 'two', 'three_{}'.format('_'.join((a,b)))]
Out[6]: ['one', 'two', 'three_four_five']