Chandan Kumar
Chandan Kumar

Reputation: 148

how to concatenate a string and a variable and assign a value in it in python

Is there anyway to assign value in concatenated variable?

I want to concatenate and assign a value in it.

for i in range (5):
    'serial_' + str(i) = i+5

that showing SyntaxError: can't assign to operator

Upvotes: 1

Views: 3169

Answers (2)

kalehmann
kalehmann

Reputation: 5011

It is possible to add variables with concatenated names in the global/local symbol table using the globals and locals built-in functions:

>>> for i in range (5):
...     global()['serial_' + str(i)] = i+5
... 
>>> serial_0
5
>>> serial_3
8

However according to the documentation, changing the dictionary returned by locals may have no effect to the values of local variables used by the interpreter.

Furthermore since modifying the global symbol table is not considered a good practice, I recommend you to use a dictionary to store your values as suggested by Mayank Porwal as this will result in cleaner code:

>>> d = {f'serial_{i}' : i + 5 for i in range(5)}
>>> d
{'serial_0': 5, 'serial_1': 6, 'serial_2': 7, 'serial_3': 8, 'serial_4': 9}

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34056

If I understand correctly,

d = {}
In [898]: for i in range (5):
     ...:    d[ ('{}' + str(i)).format('serial_')] = i+5


In [899]: d
Out[899]: {'serial_0': 5, 'serial_1': 6, 'serial_2': 7, 'serial_3': 8, 'serial_4': 9}

Let me know if this is what you want.

Upvotes: 1

Related Questions