python - python3.5中使用split函数

标签 python python-3.x

尝试在数字 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() without removing the delimiter 的副本因为分隔符必须是第二个字符串的一部分。

最佳答案

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

>>> 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')

关于python - python3.5中使用split函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48950806/

相关文章:

python - BeautifulSoup 网页抓取多个页面 URL 不会改变

python - 在 64 位 Windows 上从哪里获取和安装 crypto.dll

python-3.x - 如何使用elasticsearch-dsl-py创建 “In”条件过滤器?

python-3.x - 反转元组列表中的数字

python - 如何将数组转换为 0 或 1 个元素?

python - 如何使用 Django REST 序列化程序对保留键进行验证?

python - 无法从本地服务器外部连接到 Django

python - python3中的互斥锁

Python:用括号比较和替换列表[i]

python-3.x - 通过 Falcon 在正文中发送 CSV