0

i have tried the below code and getting results s i mentioned below.

code:

yday_mnth = '201905'
b = yday_mnth
x = 'yday_mnth'
print b
print x

Output here is as below:

201905
yday_mnth

Which means for b am getting value as 201905 however for x I'am getting yday_mnth as its a string however is there any way to convert the x to print value of yday_mnth? i.e 201905

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
Naveen
  • 1
  • 1
  • If you want `x` to have the same value as `yday_mnth`, then you can simply do `x = yday_mnth`... But I suspect you know this already, because that's exactly how you defined `b`. Can you elaborate a little more on your use case? – Kevin Apr 09 '19 at 15:02
  • remove the quotes of `'yday_mnth'` – Pedro Lobito Apr 09 '19 at 15:02
  • 1
    I think Naveen might be looking for the `eval` function in this case. In your example, `eval('yday_mnth')` would do the trick - however, using `eval` is generally not recommended, so please use with caution. – Aquarthur Apr 09 '19 at 15:05
  • I suspect what you're really saying is 'I don't know what value x has until runtime. It could be "yday_mnth" or "foobar" or "baz", and in each of these cases I want x's value to become the value of whatever variable it's holding the name of'. This is an antipattern commonly known as "variable variables" and it's almost always a bad idea. Related reading: [How do I create a variable number of variables?](https://stackoverflow.com/q/1373164/953482) – Kevin Apr 09 '19 at 15:05
  • `globals()[x]` Be gentle :) Depending on the scope, ofcourse – han solo Apr 09 '19 at 15:15

0 Answers0