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

时间:2014-12-10 09:34:34

标签: python regex string split

如何以最有效的方式定义字符串分隔符以进行拆分?我的意思是不需要使用很多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以检查其他分隔符,如': '。但后来我想知道是否有更好的方法来定义它们(如果我需要在某种列表中包含新的分隔符,如果我以后需要的话,则没有问题)。也许正则表达式可以帮助或其他一些工具?

4 个答案:

答案 0 :(得分:4)

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

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

如果您想进行一次分割,请添加maxsplit=1

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

答案 1 :(得分:1)

您可以使用re模块的split功能

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

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

答案 2 :(得分:0)

\s*[:-]\s*

您可以按此分割。使用re.split(r"\s*[:-]\s*",string)。请参阅演示。

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

如果您可以使用---等分隔符,则应使用此分区。其中您可以有多个空格。

答案 3 :(得分:0)

这不是最好的方法,但是如果你想避免因某些(或没有)原因使用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块更少,而且您不必导入任何内容。

相关问题