简体   繁体   中英

How to convert string into an variable in python

I am trying to read an string from a text file. After I read it I want to convert it into an array or variable. In the text file I can read 'b' I sign 'b' to x, x='b' ,and I want to use how can I put 'b' as a variable b so that s = sin(2*pi*x) is s = sin(2*pi*b) .

Object: I am trying to setup a configure file so that I could easily change the varibles of input from the textfile.

Final step is that I can print it out.

b = arange(0.0, 4.0, 0.01)
t = arange(0.0, 2.0, 0.01)
x = ['b'] // result after I read from the file
x = changestringtoVarible('b')

s = sin(2*pi*x)
plot(x, s)
xlabel('time(s)')
ylabel(y)
title(ttl)
grid(True)

I want to choose if I use b or t as xaxis from the text file, that is why I asked this.

You're doing a primitive form of parsing. Your variable x will contain the character 'b' or 't', and you want use that to control how an expression is evaluated. You can't use the variable x directly in the expression, because it just contains a character. You have to execute different code depending on its value. For a simple case like this, you can just use an if construct:

...
b = arange(0.0, 4.0, 0.01)
t = arange(0.0, 2.0, 0.01)

if x == 'b':
    xvalue = b
elif x == 't'
    xvalue = t

s = sin(2*pi*xvalue)
plot(xvalue, s)
...

For a larger number of cases, you can use a dictionary:

...
xvalues = { 'b' : arange(0.0, 4.0, 0.01),
            't' : arange(0.0, 2.0, 0.01),
            # More values here
          }

xvalue = xvalues[x]
s = sin(2*pi*xvalue)
plot(xvalue, s)
....

You can use eval.

For example:

b='4'
formula = "2*x"
formula = formula.replace("x", "%d")
Result = eval(formula % int(b))

If you just want to use a string as a variable you can use pythons exec function:

>>> exec("some_string"+"=1234")
>>> some_string
1234

update:

You better want to use another name for the x variable in s = sin(2*pi*x) , we might call x y from now on.

b = arange(0.0, 4.0, 0.01)
t = arange(0.0, 2.0, 0.01)

Assumed that x defines which one should be used, you can use the following code to assign it to a variable:

exec("y"+"="+x)
s = sin(2*pi*y)

That one should work. But i would recommend you to change you code to something more solid (eg using a dictionary).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM