Fetching a substring after first place in Python

I need help with regex or Python to extract a substring from a set of strings. A string consists of alphanumeric characters. I just want the substring to start after the first space and end before the last space, as shown 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'm in, is there an easy way to extract strings before or after a specific character? For example, I want to extract a date or day, as from a string similar to the one shown in Example 2.

 Example 2: Date:30/4/2013 Day:Tuesday Results: 30/4/2013 Tuesday 

I really read about regex, but this is very alien to me. Thanks.

+4
source share
3 answers

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' 
+6
source
 >>> s="A:01 What is the date of the election ?" >>> s.split(" ", 1)[1].rsplit(" ", 1)[0] 'What is the date of the election' >>> 
+5
source

There is no need to embed in a regular expression if thatโ€™s 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 worryโ€:

 _,_,theReallyAwesomeDay = s.partition(':') 
+1
source