我想编写一个将字符串拆分成多个空格而不是单个空格的函数。
示例:
sample_string = "2012.03.04 check everything status: OK"
split_string = ["2012.03.04", "check everything", "status: OK"]
如何在不使用丑陋的for循环的情况下从sample_string
到split_string
?
答案 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)
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']