在两个步骤中使用字符串中的.format()

Lui*_*uez 4 python string string-formatting

我有一个字符串,我想在其中替换一些变量,但在不同的步骤中,类似于:

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')
Run Code Online (Sandbox Code Playgroud)

但是当我尝试替换第一个变量时,我得到一个错误:

KeyError: 'var_2'
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

编辑:我想创建一个新列表:

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 ]
Run Code Online (Sandbox Code Playgroud)

这是所需的输出:

['text_with_Luis_to_variables_12344',
 'text_with_Luis_to_variables_553454',
 'text_with_Luis_to_variables_dadada']
Run Code Online (Sandbox Code Playgroud)

但是使用.format而不是.replace.

Moi*_*dri 6

在简单的话,你不能用格式替换一些参数{var_1},var_2在字符串(不是全部)使用format.虽然我不确定为什么你只想替换部分字符串,但是你可以采用几种方法作为解决方法:

方法1:通过更换你想在第二个步骤,以替换变量{{}}来代替{}.例如:替换{var_2}{{var_2}}

>>> my_string = 'text_with_{var_1}_to_variables_{{var_2}}'
>>> my_string = my_string.format(var_1='VAR_1')
>>> my_string
'text_with_VAR_1_to_variables_{var_2}'
>>> my_string = my_string.format(var_2='VAR_2')
>>> my_string
'text_with_VAR_1_to_variables_VAR_2'
Run Code Online (Sandbox Code Playgroud)

方法2:使用替换一次,使用format另一次%.

>>> my_string = 'text_with_{var_1}_to_variables_%(var_2)s'
# Replace first variable
>>> my_string = my_string.format(var_1='VAR_1')
>>> my_string
'text_with_VAR_1_to_variables_%(var_2)s'
# Replace second variable
>>> my_string  = my_string % {'var_2': 'VAR_2'}
>>> my_string
'text_with_VAR_1_to_variables_VAR_2'
Run Code Online (Sandbox Code Playgroud)

方法3:添加args到a dict并在需要时将其解压缩.

>>> my_string = 'text_with_{var_1}_to_variables_{var_2}'
>>> my_args = {}
# Assign value of `var_1`
>>> my_args['var_1'] = 'VAR_1'
# Assign value of `var_2`
>>> my_args['var_2'] = 'VAR_2'
>>> my_string.format(**my_args)
'text_with_VAR_1_to_variables_VAR_2'
Run Code Online (Sandbox Code Playgroud)

使用满足您要求的那个.:)