0

If I have a string like this:

string = "12345|67891|23456|123456?"

how would I take out the "12345" and the "67891", etc (the characters between the pipes) and add them to a list all the way until the question mark (I am using the question mark in my code as a terminating character)?

A similar question has been asked here: How do I find the string between two special characters?

but I think mine is different because I need to do it multiple times in the same, one-line string.

Here is what I am hoping to achieve:

[PROGRAM BEGINS]
>>>string = "12345|67891|23456|123456?"
>>>string_list = []
>>>#some code to extract it and add it to a list called string_list
>>>print string_list
["12345","67891","23456","123456"]
[PROGRAM TERMINATES]

Thanks in advance!!

3
  • 1
    You want to use the split function Commented Jul 14, 2015 at 1:49
  • 1
    Are you trying to extract only the digits or the ? should be included as well? Commented Jul 14, 2015 at 1:55
  • @KhalilAmmour-خليلعمور only the digits Commented Jul 14, 2015 at 1:57

6 Answers 6

2

If the question mark is always at the end.

>>> string = "12345|67891|23456|123456?"
>>> string.rstrip('?').split('|')
['12345', '67891', '23456', '123456']

regex are relatively slow for performing tasks like this

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

Comments

1

You don't need to use the question mark:

>>> string = "12345|67891|23456|123456"
>>> string.split('|')
['12345', '67891', '23456', '123456']
>>>

2 Comments

Its says I have to wait nine minutes to mark this as correct...but I will. Thanks!
Also, I had the question mark because I thought I was going to need like a for loop or something. XD
1

You can use regex to split on anything which is not a digit \D:

import re

matches = filter(None, re.split('\D', "12345|67891|23456|123456?"))
print matches # ['12345', '67891', '23456', '123456']

Comments

1

You can do it with re module, this way:

>>>import re
>>>s = "12345|67891|23456|123456?"
>>>string_list = re.findall(r'\d+',s)
>>>string_list
['12345', '67891', '23456', '123456']

Comments

1

You can use the split function. Str.split("|") and assign the result to an array variable.

Comments

1

Considering you are using '?' as a terminating char. The safest way to do this would be:

>>> string = "12345|67891|23456|123456?"
>>> string.split('?')[0].split('|')
['12345', '67891', '23456', '123456']

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.