简体   繁体   English

如何在python中将字符串转换为变量

[英]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) . 在文本文件中,我可以读取“ b”,然后将“ b”签名为x, x='b' ,并且我想使用如何将'b'作为变量b使s = sin(2*pi*x)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. 我想选择是否使用bt作为文本文件的xaxis,这就是为什么我问这个问题。

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. 您的变量x将包含字符“ b”或“ t”,并且您想使用它来控制表达式的求值方式。 You can't use the variable x directly in the expression, because it just contains a character. 您不能在表达式中直接使用变量x,因为它仅包含一个字符。 You have to execute different code depending on its value. 您必须根据其值执行不同的代码。 For a simple case like this, you can just use an if construct: 对于像这样的简单情况,您可以仅使用if构造:

...
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. 您可以使用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: 如果只想将字符串用作变量,则可以使用pythons exec函数:

>>> 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. 您最好在s = sin(2*pi*x)x变量使用另一个名称,从现在开始我们可能会调用x y

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: 假设x定义了应使用的x ,则可以使用以下代码将其分配给变量:

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). 但我建议您将代码更改为更可靠的内容(例如,使用字典)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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