在第二次出现任何数字后拆分字符串?

Split string after second occurence of any digit?

我想在任何数字出现两次后拆分一个字符串(如果可能的话用换行符)。或者换句话说:用换行符替换第二个数字后的每个 space。或者将它们放入列表中也可以。

a = "4 one 3 5 two two 6 6 three 14 7 four four four 7"
"\n".join(a.split("\d", 2)[:2])

应该return

"4 one 3"
"5 two two 6"
"6 three 14"
"7 four four four 7"

re.split 与 space 以及数字的前瞻和后视断言一起使用:

import re

re.split(r"(?<=\d) (?=\d)", a)
# ['4 one 3', '5 two two 6', '6 three 14', '7 four four four 7']
import re
a = "4 one 3 5 two two 6 6 three 14 7 four four four 7"
indices = [x.start() for x in re.finditer('\d+', a)] #Find out all indices where digit 0 to 9 is occurred.
result = []
for i in range(0, len(indices),2):   # i traverses through all indices
    result.append(a[indices[i]:indices[i+1]+1]) # String slicing is
for s in result:
    print(s)

从奇数出现的数字[0-9]到偶数出现的数字[0-9]进行字符串切片,并将其附加到列表中。

输出

4 一 3

5 二二 6

6 三 14

7 四四四 7

import re
a = "4 one 3 5 two two 6 6 three 14 7 four four four 7"
result = re.split(r"(?<=\d) (?=\d)", a)
for s in result:
    print(s)

输出

4 一 3

5 二二 6

6 三 14

7 四四四 7