[英]Using split function in python3.5
试图在数字7
处拆分字符串,我希望将 7 包含在拆分字符串的第二部分中。
代码:
a = 'cats can jump up to 7 times their tail length'
words = a.split("7")
print(words)
输出:
['cats can jump up to ', ' times their tail length']
字符串被拆分,但第二部分不包括 7。
我想知道如何包含 7。
注意:在不删除分隔符的情况下,不是Python split()的副本,因为分隔符必须是第二个字符串的一部分。
一个简单而天真的方法就是找到你想要分割的索引并将其切片:
>>> 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')
另一种方法是使用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')
要在后面部分再次加入数字,您可以使用str.join
:
x, *y = a.partition('7')
y = ''.join(y)
print((x, y))
# ('cats can jump up to ', '7 times their tail length')
或者手动执行:
sep = '7'
x = a.split(sep)
x[1] = sep + x[1]
print(tuple(x))
# ('cats can jump up to ', '7 times their tail length')
在一行中,对字符串的其余部分使用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])
结果:
['cats can jump up to ', '7 times their tail length']
在 split regex 中使用()
告诉re.split
不要丢弃分隔符。 A (7)
regex 本来可以工作,但会像str.partition
那样创建一个 3 项列表,并且需要一些后期处理,所以没有单行。
现在,如果数字未知,正则表达式(再次)是最好的方法。 只需将代码更改为:
[x for x in re.split("(\d.*)",a) if x]
re 也可用于全局捕获:
>>> s = 'The 7 quick brown foxes jumped 7 times over 7 lazy dogs'
>>> sep = '7'
>>>
>>> [i for i in re.split(f'({sep}[^{sep}]*)', s) if i]
['The ', '7 quick brown foxes jumped ', '7 times over ', '7 lazy dogs']
如果 f 字符串难以阅读,请注意它的计算结果为(7[^7]*)
。
(为了与 listcomp 相同,可以使用list(filter(bool, ...))
,但它相对来说相当丑陋)
在 Python 3.7 及re.split()
, re.split()
允许在零宽度模式上进行拆分。 这意味着可以使用前瞻正则表达式f'(?={sep})'
代替上面显示的组。
奇怪的是时间:如果使用re.split()
(即没有编译的模式对象),组解决方案的运行速度始终比前瞻快 1.5 倍。 但是,在编译时,前瞻击败了其他人:
In [4]: r_lookahead = re.compile('f(?={sep})')
In [5]: r_group = re.compile(f'({sep}[^{sep}]*)')
In [6]: %timeit [i for i in r_lookahead.split(s) if i]
2.76 µs ± 207 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [7]: %timeit [i for i in r_group.split(s) if i]
5.74 µs ± 65.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [8]: %timeit [i for i in r_lookahead.split(s * 512) if i]
137 µs ± 1.93 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [9]: %timeit [i for i in r_group.split(s * 512) if i]
1.88 ms ± 18.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
递归解决方案也可以正常工作,尽管比在编译的正则表达式上拆分要慢(但比直接re.split(...)
快):
def splitkeep(s, sep, prefix=''):
start, delim, end = s.partition(sep)
return [prefix + start, *(end and splitkeep(end, sep, delim))]
>>> s = 'The 7 quick brown foxes jumped 7 times over 7 lazy dogs'
>>>
>>> splitkeep(s, '7')
['The ', '7 quick brown foxes jumped ', '7 times over ', '7 lazy dogs']
使用枚举,这仅在字符串不以分隔符开头时才有效
s = 'The quick 7 the brown foxes jumped 7 times over 7 lazy dogs'
separator = '7'
splitted = s.split(separator)
res = [((separator if i > 0 else '') + item).strip() for i, item in enumerate(splitted)]
print(res)
['The quick', '7 the brown foxes jumped', '7 times over', '7 lazy dogs']
[Program finished]
还可以使用split
和列表理解来完成所有这些工作,而无需导入任何库。 但是,这会使您的代码稍微“不那么漂亮”:
a = 'cats can jump up to 7 times their tail length'
sep = '7'
splitString = a.split(sep)
splitString = list(splitString[0]) + [sep+x for x in splitString[1:]]
有了这个, splitString
将携带值:
['cats can jump up to ', '7 times their tail length']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.