Python Question

use .format() in a string in two steps

I have a string in which I want to replace some variables, but in different steps, something like:

my_string = 'text_with_{var_1}_to_variables_{var_2}'
### make process 1

But when I try to replace the first variable I get an Error:

KeyError: 'var_2'

How can I accomplish this?

I want to create a new list:

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 ]

this is the desired output:


But using .format instead of .replace.

Answer Source

In simple words, you can not replace few arguments with format {var_1}, var_2 in string(not all) using format. Even though I am not sure why you want to only replace partial string, but there are few approaches that you may follow as a workaround:

Approach 1: Replacing the variable you want to replace at second step by {{}} instead of {}. For example: Replace {var_2} by {{var_2}}

>>> my_string = 'text_with_{var_1}_to_variables_{{var_2}}'
>>> my_string = my_string.format(var_1='VAR_1')
>>> my_string
>>> my_string = my_string.format(var_2='VAR_2')
>>> my_string

Approach 2: Replace once using format and another using %.

>>> 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
# Replace second variable
>>> my_string  = my_string % {'var_2': 'VAR_2'}
>>> my_string

Approach 3: Adding the args to a dict and unpack it once required.

>>> 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)

Use the one which satisfies your requirement. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download