Python - 定义字符串拆分分隔符



如何定义字符串分隔符以最有效的方式进行拆分?我的意思是不需要使用很多 if 等?

我有字符串需要严格拆分为两个元素列表。问题是这些字符串有不同的符号,我可以通过这些符号来拆分它们。例如:

'Hello: test1' .这个有拆分分隔符': '.另一个例子是: 'Hello - test1' .所以这个会' - '.拆分分隔符也可以是' -''- '。因此,如果我知道分隔符的所有变体,我如何才能最有效地定义它们?

首先,我做了这样的事情:

strings = ['Hello - test', 'Hello- test', 'Hello -test']
for s in strings:
    delim = ' - '
    if len(s.split('- ', 1)) == 2:
        delim = '- '
    elif len(s.split(' -', 1)) == 2:
        delim = ' -'
    print s.split(delim, 1)[1])

但后来我得到了新的字符串,它有另一个意想不到的分隔符。因此,这样做我应该添加更多ifs来检查其他分隔符,例如': '。但后来我想知道是否有更好的方法来定义它们(如果我以后需要的话,如果我需要在某种列表中包含新的分隔符,那就没有问题了)。也许正则表达式会有所帮助或其他工具?

将所有分隔符放在函数re.split,如下所示使用逻辑 OR |运算符。

re.split(r': | - | -|- ', string)

如果要执行一次性拆分,请添加maxsplit=1

re.split(r': | - | -|- ', string, maxsplit=1)

您可以使用 re 模块的拆分功能

>>> strings = ['Hello1 - test1', 'Hello2- test2', 'Hello3 -test3', 'Hello4 :test4', 'Hello5 : test5']
>>> for s in strings:
...   re.split(" *[:-] *",s)
...
['Hello1', 'test1']
['Hello2', 'test2']
['Hello3', 'test3']
['Hello4', 'test4']
['Hello5', 'test5']

[]之间放置所有可能的分隔符。*表示某些空格可以放在之前或之后。

s*[:-]s*

你可以通过这个分裂。使用re.split(r"s*[:-]s*",string) .请参阅演示。

https://regex101.com/r/nL5yL3/14

如果你可以有像--这样的分隔符,或者-,你应该使用它,其中你可以有多个空格。

这不是最好的方法,但如果你想避免使用re出于某种(或没有)原因,这就是我会做的:

>>> strings = ['Hello - test', 'Hello- test', 'Hello -test', 'Hello : test']
>>> delims = [':', '-']  # all possible delimiters; don't worry about spaces.
>>>
>>> for string in strings:
...     delim = next((d for d in delims if d in string), None) # finds the first delimiter in delims that's present in the string (if there is one)
...     if not delim:
...         continue  # No delimiter! (I don't know how you want to handle this possibility; this code will simply skip the string all together.)
...     print [s.strip() for s in string.split(delim, 1)]  # assuming you want them in list form.
['Hello', 'test']
['Hello', 'test']
['Hello', 'test']
['Hello', 'test']

这使用 Python 的本机.split()在分隔符处断开字符串,然后.strip()修剪结果中的空格(如果有)。我用next来找到合适的分隔符,但是有很多东西可以换掉(特别是如果你喜欢for块)。

如果您确定每个字符串将至少包含一个分隔符(最好正好包含一个),则可以将其缩减为:

 ## with strings and delims defined...
>>> for string in strings:
...     delim = next(d for d in delims if d in string) # raises StopIteration at this line if there is no delimiter in the string.
...     print [s.strip() for s in string.split(delim, 1)]

我不确定这是否是最优雅的解决方案,但它使用更少的if块,您无需导入任何东西即可执行此操作。

最新更新