在多个空格上分割字符串,但不能在单个空格上分割

时间:2019-05-20 14:37:53

标签: python regex

我想编写一个将字符串拆分成多个空格而不是单个空格的函数。

示例:

sample_string = "2012.03.04       check everything      status: OK"
split_string = ["2012.03.04", "check everything", "status: OK"]

如何在不使用丑陋的for循环的情况下从sample_stringsplit_string

4 个答案:

答案 0 :(得分:4)

>>> import re
>>> help(re.split)
Help on function split in module re:

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.  If
    capturing parentheses are used in pattern, then the text of all
    groups in the pattern are also returned as part of the resulting
    list.  If maxsplit is nonzero, at most maxsplit splits occur,
    and the remainder of the string is returned as the final element
    of the list.

>>> re.split(r'\s{2,}', "2012.03.04       check everything      status: OK")
['2012.03.04', 'check everything', 'status: OK']

答案 1 :(得分:3)

您可以使用re.split()。 (test link)。

代码:

import re

sample_string = "2012.03.04       check everything      status: OK"

print(re.split("\s{2,}", sample_string))

输出:

['2012.03.04', 'check everything', 'status: OK']

答案 2 :(得分:2)

使用regular expressions

cd ~/.rbenv/plugins/ruby-build
git pull

将返回您

import re sample_string = "2012.03.04 check everything status: OK" REGEX = re.compile(r' {2,}') # Two or more spaces re.split(REGEX, sample_string)

答案 3 :(得分:2)

使用re软件包:

import re
re.split(r'\s{2,}', sample_string)

输出:

['2012.03.04', 'check everything', 'status: OK']