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

2024-06-28 11:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份街道地址清单,其中有些有邮政信箱。我想做的是删除任何不是邮政信箱的行,如果它确实包含邮政信箱。例如,如果有一个列表['123 whatever drive','234 anywhere lane po box 3213','po box 190 441 bettername street'],则应返回['123 whatever drive','po box 3213','po box 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”后面的空格作为分隔符,抓住空格后面的下一个数字子串,然后用下一个空格作为分隔符来结束字符串,但我想不出怎么做。你知道吗


Tags: inbox列表地址drive街道poanywhere
3条回答

您可以使用regex,这里很容易测试:https://pythex.org/

import re
firstList = ['123 whatever drive', '234 anywhere lane po box 3213', 'po box 190 441 bettername street']
outputList = [re.search('[0-9]+', x)[0] if 'po box' in x else x for x in firstList]

将输出:

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

这应该起作用:

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']

使用列表理解:

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执行此操作。你知道吗

如果您想更具体一些,可以考虑使用regular expressions而不是字符串切片。你知道吗

相关问题 更多 >