0

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?

  • 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 Answers2

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
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