1

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?

7
  • Have you tried splitting on commas and performing lstrip on the remaining string? Commented Mar 13, 2016 at 18:49
  • 1
    What is the exact output that you want? Commented Mar 13, 2016 at 18:50
  • What code have you tried? Commented Mar 13, 2016 at 18:50
  • I want output to be in this format: name1 = query.split(1) name2 = query.split(2) name3 = .... Commented Mar 13, 2016 at 18:52
  • @EV3REST Can you write a sample output, like an actual string that demonstrates what you're looking for? Commented Mar 13, 2016 at 18:53

3 Answers 3

1

Use query.split(',')[1].split('name')

Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

i have more than 2 'names' in the string, so i need to skip n amount of characters, that's what I was asking.
@EV3REST Skip until you reach what? What's your expected output?
@EV3REST There, that should do it.
I need to have different names in different virables, and names count is more than 2
@EV3REST You don't need different variables and that works for any number of names. names[0] will be Alan, names[1] will be Jake and so on.
0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.