Reputation: 105
I have my string in variable:
query = 'name=Alan age=23, name=Jake age=24'
how do I split my string on name=Jake
instead of name=Alan
?
Don't suggest query.split(name=Alan)
, it won't work in my case.
I need something that will skip first name
and continue searching for second, and then do split. So, how can i do that?
Upvotes: 1
Views: 317
Reputation: 532
Try this:
query = 'name=Alan age=23, name=Jake age=24'
names = [y.split(" ")[0][5:] for y in (x.strip() for x in query.split(","))]
print(names)
Output:
['Alan', 'Jake']
Upvotes: 0
Reputation: 2345
You can try splitting on the comma and then on the spaces like so:
query = 'name=Alan age=23, name=Jake age=24'
query_split = [x.strip() for x in query.split(",")]
names = [a.split(" ")[0][5:] for a in query_split]
print(names)
['Alan', 'Jake']
With this you don't need multiple variables since all your names will be in the list names
, you can reference them by names[0]
, names[1]
and so on for any given number of names.
Upvotes: 0