Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}'
my_string.format(var_1='10')
### make process 1
my_string.format(var_2='22')

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

KeyError: 'var_2'

How can I accomplish this?

Edit: 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:

['text_with_Luis_to_variables_12344',
 'text_with_Luis_to_variables_553454',
 'text_with_Luis_to_variables_dadada']

But using .format instead of .replace.

like image 579
Luis Ramon Ramirez Rodriguez Avatar asked Dec 25 '22 02:12

Luis Ramon Ramirez Rodriguez


1 Answers

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

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

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

Use the one which satisfies your requirement. :)

like image 174
Moinuddin Quadri Avatar answered Jan 08 '23 12:01

Moinuddin Quadri