how to extract the integers from the string(integers separated by space) and assign them to different variables.
eg.
Given string: "2 3 4 5"
assign: n=2, m=3, x=4, y=5
2 Answers
Something like (read comments):
>>> s = "2 3 4 5"
>>> s.split() # split string using spaces
['2', '3', '4', '5'] # it gives you list of number strings
>>> n, m, x, y = [int(i) for i in s.split()] # used `int()` for str --> int
>>> n # iterate over list and convert each number into int
2 # and use unpack to assign to variables
2 Comments
L = [int(i) for i in s.split()] now I can use any elements as L[j] for j < len(L), Generally in programming languages we uses arrays(or in Python say list) when we need many variables.the number of values in your string might be variable. In this case you could assign the variables to a dictionnary as follows:
>>> s = "2 3 4 5"
>>> temp = [(count, int(value)) for count, value in enumerate(s.split(' '), 1)]
>>> vars = {}
>>> for count, value in temp:
... vars['var' + str(count)] = value
>>> vars
{'var4': 5, 'var1': 2, 'var3': 4, 'var2': 3}
>>> vars['var2']
3
If you really don't want a dictionnary, you could consider the following:
>>> temp = [(count, int(value)) for count, value in enumerate(s.split(' '), 1)]
>>> for count, value in temp:
... locals()['var{}'.format(count)] = value
>>> var2
3
locals()['var{}'.format(count)] = value will add a local variable named 'var{count}' and assign the value to it. locals()shows you the local variables and its values.
Remember: do this only if you really know what you are doing. Read please also the note on locals in the Python documentation: "The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter."
7 Comments
var = dict(( "var" + str(count), int(value)) for count, value in enumerate(s.split()) in one line .... if someone uses Python3 then he can write expression in { } dict compression. ..but your dict idea is good.vars() scope but I read somewhere that behavior is undefined (I guess in Apress). I am not sure about But if it is a defined behavior, then it is very very good answer. I am kinda learn in Python.
s = "2, 3, 45, a, b, 5,"then you can usere.findall(r'\d+', s)to convert into list of number strings.