Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用空格作为分隔符来获取字符串中的子字符串?_Python_String_Python 3.x - Fatal编程技术网

Python 如何使用空格作为分隔符来获取字符串中的子字符串?

Python 如何使用空格作为分隔符来获取字符串中的子字符串?,python,string,python-3.x,Python,String,Python 3.x,我有一个街道地址列表,其中一些有邮箱。我要做的是,如果行中确实包含一个邮政信箱,则从行中删除任何不是邮政信箱的内容。例如,如果有一个列表['123任意车道','234 anywhere lane邮政信箱3213','邮政信箱190 441 bettername street'],则应返回['123任意车道','邮政信箱3213','邮政信箱190']。 到目前为止,我所拥有的只是 def listofaddr(lst)): boxes = ('po box ', 'p o box ')

我有一个街道地址列表,其中一些有邮箱。我要做的是,如果行中确实包含一个邮政信箱,则从行中删除任何不是邮政信箱的内容。例如,如果有一个列表['123任意车道','234 anywhere lane邮政信箱3213','邮政信箱190 441 bettername street'],则应返回['123任意车道','邮政信箱3213','邮政信箱190']。 到目前为止,我所拥有的只是

def listofaddr(lst)):
    boxes = ('po box ', 'p o box ')
    finstring = []
    for i in lst:
        if boxes in i:
            i = 'po box ' + 
        finstring.append(i)

我想我能做的是使用“box”后面的空格作为分隔符,抓取空格后面的下一个数字子字符串,然后使用下一个空格作为分隔符结束字符串,但我想不出怎么做。

使用列表理解:

addrs = ['123 whatever drive', '234 anywhere lane po box 3213', 'po box 190 441 bettername street']
boxes = [(a[a.index('po box'):] if ('po box' in a) else a) for a in addrs]
我在这里使用的是简单的字符串切片:如果字符串
'po box'
存在于任何地址
a
中,请切掉该点之前的字符串部分。否则,只需返回地址
a
,并对
addrs
中的所有地址
a
执行此操作

如果您想变得更具体,可以研究使用而不是字符串切片。

这应该可以:

a=['123 whatever drive', '234 anywhere lane po box 3213', 'po box 190 441 bettername street']
["po box "+e.split("po box ")[1].split(" ")[0] if "po box" in e else e for e in a]
输出:

['123 whatever drive', 'po box 3213', 'po box 190']

您可以使用regex,这里很容易测试:

将输出:

['123 whatever drive', 'po box 3213', 'po box 190']

我想他们想要邮箱后面的具体数字,而不是邮箱后面的所有数字
['123 which drive'、'po box 3213'、'po box 190 441 bettername street']
不是
['123 which drive'、'po box 3213'、'po box 190']
输入列表
e
是循环变量
['123任意驱动器','po box 3213','po box 190']
['123任意驱动器','po box 3213','po box 190 441']
不同。根据OP的问题,这不是预期的结果。@Christopherasa再次阅读OP的问题。他们不想要411。他们只需要第一组数字。
['123 whatever drive', 'po box 3213', 'po box 190']