在python3.5中使用split函数

Sam*_*ain 4 python python-3.x

尝试将字符串拆分为数字7,我希望7包含在拆分字符串的第二部分中.

码:

a = 'cats can jump up to 7 times their tail length'

words = a.split("7")

print(words)
Run Code Online (Sandbox Code Playgroud)

输出:

['cats can jump up to ', ' times their tail length']
Run Code Online (Sandbox Code Playgroud)

字符串被拆分但第二部分不包括7.

我想知道如何包含7.

注意:不要删除分隔符而不是Python split()的副本,因为分隔符必须是第二个字符串的一部分.

Raf*_*ros 5

一个简单而天真的方法就是找到你要拆分的索引并将其切片:

>>> a = 'cats can jump up to 7 times their tail length'
>>> ind = a.index('7')
>>> a[:ind], a[ind:]
('cats can jump up to ', '7 times their tail length')
Run Code Online (Sandbox Code Playgroud)

  • @SreeramTP如果分隔符重复,那么OP应该在问题中提到. (3认同)

Gra*_*her 5

另一种方法是使用str.partition

a = 'cats can jump up to 7 times their tail length'
print(a.partition('7'))
# ('cats can jump up to ', '7', ' times their tail length')
Run Code Online (Sandbox Code Playgroud)

要在后半部分重新加入数字,您可以使用str.join

x, *y = a.partition('7')
y = ''.join(y)
print((x, y))
# ('cats can jump up to ', '7 times their tail length')
Run Code Online (Sandbox Code Playgroud)

或手动执行:

sep = '7'
x = a.split(sep)
x[1] = sep + x[1]
print(tuple(x))
# ('cats can jump up to ', '7 times their tail length')
Run Code Online (Sandbox Code Playgroud)


Jea*_*bre 5

在一行中,re.split与字符串的其余部分一起使用,并过滤剩下的最后一个空字符串re.split

import re
a = 'cats can jump up to 7 times their tail length'
print([x for x in re.split("(7.*)",a) if x])
Run Code Online (Sandbox Code Playgroud)

结果:

['cats can jump up to ', '7 times their tail length']
Run Code Online (Sandbox Code Playgroud)

using ()in split regex 告诉re.split不要丢弃分隔符。一个(7)正则表达式会的工作,但将创造3项列表喜欢str.partition做,并会需要进行一些后期处理,所以没有一个班轮。

现在,如果数字未知,正则表达式(再次)是最好的方法。只需将代码更改为:

[x for x in re.split("(\d.*)",a) if x]
Run Code Online (Sandbox Code Playgroud)