I am trying to read a string and if it contains something like "x=2" I want to set x to 2. How can I do that?
Asked
Active
Viewed 39 times
0
-
1`exec("x=2")`.. – ForceBru Jan 09 '21 at 17:40
-
Welcome to SO. This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask] and the other links found on that page. [“Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). – wwii Jan 09 '21 at 17:43
-
Your question is pretty broad - are you having trouble with: reading a string?, parsing the string?, dynamically creating a variiable?... Make sure you read [mre] when reading through the links from the previous comment. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem. – wwii Jan 09 '21 at 17:45
-
Doing this is almost never a good idea. Consider accepting the string and storing it in a `dict`. For example `exp=input(); k,_,v = exp.partition("="); myvalues[k]=v`. – BoarGules Jan 09 '21 at 18:05
2 Answers
0
If you have a string s
in the form "var=number"
then you can simply do
r = s.split("=")
var, number = (r[0], int(r[1]))
locals()[var] = number
See this for more explanations about locals()
.

Thibault D.
- 201
- 1
- 4
-
How can I call the variable then? I just get an error message when using it. – ItzZanty Jan 09 '21 at 17:47
-
What do you mean by "call the variable"? And what error message do you get? – Thibault D. Jan 09 '21 at 17:49
-
By call I mean to use it in any context. For example print(x). And in the error message it just says that the variable is not defined. – ItzZanty Jan 09 '21 at 17:53
-
1What is your code that gives an error? Otherwise, `locals()["x"]` is equivalent to `x`, so you can use it however you want. – Thibault D. Jan 09 '21 at 17:55
-
It is 'result = eval(e.get())' that causes a problem. So for example if it does eval("x+2"). – ItzZanty Jan 09 '21 at 18:00
0
def replace(s):
assert(len(s)>=3)
s = s.replace("=", "")
s_list = list(s)
for i in range(1, len(s_list)):
if(s_list[i].isdigit()):
s_list[i-1] = s_list[i]
s_list[i]=''
return (''.join(s_list))
replace('abcf=3sdf=2ad=1') #'abc3sd2a1'

Epsi95
- 8,832
- 1
- 16
- 34