Convert string to variable name in python

Harshitha Palihawadana picture Harshitha Palihawadana · Oct 1, 2013 · Viewed 284.7k times · Source

I have any string. like 'buffalo',

x='buffalo'

I want to convert this string to some variable name like,

buffalo=4 

not only this example, I want to convert any input string to some variable name. How should I do that (in python)?

Answer

StefanW picture StefanW · Oct 1, 2013
x='buffalo'    
exec("%s = %d" % (x,2))

After that you can check it by:

print buffalo

As an output you will see: 2