Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting sub-string after the first space in Python

Tags:

python

regex

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.

like image 964
Cryssie Avatar asked May 01 '13 06:05

Cryssie


2 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'
like image 159
Nolen Royalty Avatar answered Sep 28 '22 13:09

Nolen Royalty


>>> s="A:01 What is the date of the election ?"
>>> s.split(" ", 1)[1].rsplit(" ", 1)[0]
'What is the date of the election'
>>> 
like image 31
Joel Cornett Avatar answered Sep 28 '22 14:09

Joel Cornett