Benjamin Hodgson
Benjamin Hodgson

Reputation: 44634

python - break string into variables

I'm sure this is going to turn out to be a stupid question... I am trying to break up a string like s = 'P1=12,P2=34,P3=56,P4=78' into a bunch of individual variables:

P1 = 12
P2 = 34
P3 = 56
P4 = 78

s.split(',') gives me a list ['P1=12','P2=34','P3=56','P4=78'], which is a start, I think. Any ideas?

Upvotes: 1

Views: 188

Answers (3)

Marconi
Marconi

Reputation: 3651

Try this:

s = 'A=1,B=2,C=3'
d = dict([i.split('=') for i in s.split(',')])
o = '%s = %s' % (', '.join(d.keys()), ', '.join(d.values()))
exec(o)

print A, B, C
# 1, 2, 3

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142156

Just double-split:

string = 'P1=12,P2=34,P3=56,P4=78'
d = dict( s.split('=') for s in string.split(',') )
# d == {'P2': '34', 'P3': '56', 'P1': '12', 'P4': '78'}

I've put these into a dict, as it may be handier for lookups depending on what you're using the data for.

If you wanted the value as an integer, you could do:

d = dict( (k, int(v)) for k, v in (s.split('=') for s in string.split(',')) )

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 601679

I'd go with something like this:

d = {}
for assignment in s.split(","):
    name, value = assignment.split("=")
    d[name.strip()] = float(value)

This will give you a dictionary mapping the names to the values, which is most probably better than trying to create variable dynamically. I f you really want to do the latter, you could also do

exec s.replace(",", "\n")

but this would be really REALLY horrible.

Upvotes: 8

Related Questions