【发布时间】:2016-08-28 21:36:35
【问题描述】:
我有一个字符串,我想在其中替换一些变量,但在不同的步骤中,例如:
my_string = 'text_with_{var_1}_to_variables_{var_2}'
my_string.format(var_1='10')
### make process 1
my_string.format(var_2='22')
但是当我尝试替换第一个变量时,我得到一个错误:
KeyError: 'var_2'
我怎样才能做到这一点?
编辑: 我想创建一个新列表:
name = 'Luis'
ids = ['12344','553454','dadada']
def create_list(name,ids):
my_string = 'text_with_{var_1}_to_variables_{var_2}'.replace('{var_1}',name)
return [my_string.replace('{var_2}',_id) for _id in ids ]
这是所需的输出:
['text_with_Luis_to_variables_12344',
'text_with_Luis_to_variables_553454',
'text_with_Luis_to_variables_dadada']
但使用 .format 而不是 .replace。
【问题讨论】:
-
不太清楚你在这里要做什么。你打算在这两个步骤之间以某种方式使用
my_string吗? -
你能解释一下你到底想要完成什么吗?这似乎是一个XY 问题。
-
我添加了一些方法,您可能会觉得有用
-
@DanielRoseman 我分两步考虑,因为第二个变量是一个列表。我更新了问题。
标签: python string string-formatting