TAGS :Viewed: 5 - Published at: a few seconds ago

[ Extracting sub-string after the first space in Python ]

I need help in regex or Python to extract a substring from a set of string. The string consists of alphanumeric. I just want the substring that starts after the first space and ends before the last space like the example given below.

Example 1:

A:01 What is the date of the election ?
BK:02 How long is the river Nile ?    

Results:
What is the date of the election
How long is the river Nile

While I am at it, is there an easy way to extract strings before or after a certain character? For example, I want to extract the date or day like from a string like the ones given in Example 2.

Example 2: 

Date:30/4/2013
Day:Tuesday

Results:
30/4/2013 
Tuesday

I have actually read about regex but it's very alien to me. Thanks.

Answer 1


I recommend using split

>>> s="A:01 What is the date of the election ?"
>>> " ".join(s.split()[1:-1])
'What is the date of the election'
>>> s="BK:02 How long is the river Nile ?"
>>> " ".join(s.split()[1:-1])
'How long is the river Nile'
>>> s="Date:30/4/2013"
>>> s.split(":")[1:][0]
'30/4/2013'
>>> s="Day:Tuesday"
>>> s.split(":")[1:][0]
'Tuesday'

Answer 2


>>> s="A:01 What is the date of the election ?"
>>> s.split(" ", 1)[1].rsplit(" ", 1)[0]
'What is the date of the election'
>>> 

Answer 3


There's no need to dig into regex if this is all you need; you can use str.partition

s = "A:01 What is the date of the election ?"
before,sep,after = s.partition(' ') # could be, eg, a ':' instead

If all you want is the last part, you can use _ as a placeholder for 'don't care':

_,_,theReallyAwesomeDay = s.partition(':')