繁体   English   中英

在Python中的第一个空格之后提取子字符串

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

我在regex或Python中需要帮助从一组字符串中提取子字符串。 该字符串由字母数字组成。 我只想要在第一个空格之后开始并在最后一个空格之前结束的子字符串,如下面给出的示例。

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

虽然我在它,有一个简单的方法来提取字符串之前或之后的字符串? 例如,我想从类似于示例2中给出的字符串中提取日期或日期。

Example 2: 

Date:30/4/2013
Day:Tuesday

Results:
30/4/2013 
Tuesday

我实际上读过有关正则表达式但它对我来说非常陌生。 谢谢。

我建议使用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'
>>> s="A:01 What is the date of the election ?"
>>> s.split(" ", 1)[1].rsplit(" ", 1)[0]
'What is the date of the election'
>>> 

如果这就是你所需要的,就没有必要深入研究正则表达式; 你可以使用str.partition

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

如果你想要的只是最后一部分,你可以使用_作为“不关心”的占位符:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM