Nikhil Garg
Nikhil Garg

Reputation: 129

Convert string into integer separated by space

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

Upvotes: 2

Views: 2262

Answers (2)

wolfrevo
wolfrevo

Reputation: 7303

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

Upvotes: 2

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

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      

Upvotes: 2

Related Questions