Skip to content
Advertisement

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,

Advertisement

Answer

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}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement