Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading