'How can I separate a string and turn it into variables

Basically, I want to separate a string and then turn every separate into a variable.

For example: If I have a string x = "2 4 6 8" how can I turn it into this: a = 2 b = 4 c = 6 d = 8

Thanks,



Solution 1:[1]

Don't generate variables dynamically, use a container.

The best is probably a list:

l = [int(e) for e in x.split()]

output: [2, 4, 6, 8]

If you really want named keys, use a dictionary:

from string import ascii_lowercase

x = "2 4 6 8"

d = dict(zip(ascii_lowercase, map(int, x.split())))

output: {'a': 2, 'b': 4, 'c': 6, 'd': 8}

Solution 2:[2]

I assume you want actual integers, not the string representation?

aslist = map(int, x.split())
a, b, c, d = aslist

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2 Francis Cagney