Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about How to convert a string to variable name in Python. so without wasting time lets learn about of this.
How to convert a string to variable name in python
- convert a string to variable name in python
to convert a string to variable name in python just Use exec(). By using exec() you can convert a string to variable name in python. Lets learn about of this by given below example:
str = "rolax" exec("%s = %d" % (str,8000)) print("output : ",rolax)
Output :output : 8000
- How to convert a string to variable name in python
to convert a string to variable name in python just Use locals(). By using locals() you can convert a string to variable name in python. Lets learn about of this by given below example:
str = "rolax" locals()[str] = 8000 print(rolax)
Output :8000
- python use string as variable name
To convert a string to variable name in python just Use exec(). By using exec() you can convert a string to variable name in python. Lets learn about of this by given below example:
str = "rolax" exec("%s = %d" % (str,8000)) print("output : ",rolax)
Output :output : 8000
Method 1: Use exec()
By using exec() you can convert a string to variable. Lets learn about of this by given below example:
str = "rolax"
exec("%s = %d" % (str,8000))
print("output : ",rolax)
Output :
output : 8000
Method 2: Use locals()
By using locals() you can convert a string to variable. Lets learn about of this by given below example:
str = "rolax"
locals()[str] = 8000
print(rolax)
Output :
8000
Method 3: Use globals()
By using globals() you can easily convert. Lets learn about of this by given below example:
str = "rolax"
globals()[str] = 8000
print(rolax)
Output :
8000
Conclusion
It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?
Also, Read