Python - 获取切片索引

标签 python python-2.7 python-2.x

是否可以获取切片的索引值(开始、结束)?例如

In [1]: s = "Test string"
In [2]: s[-6:] # get slice indexes (5,11)
Out[2]: 'string'


In [3]: s = "Another test string"
In [4]: s[8:] # get slice indexes (8,19)
Out[4]: 'test string'

换句话说,我不需要子字符串本身,只需要索引作为元组(开始,结束)。

最佳答案

您可以使用 python 的 slice像这样的对象:

In [23]: s = "Test string"

In [24]: slice(-6, None).indices(len(s))
Out[24]: (5, 11, 1)

In [25]: s = "Another test string"

In [26]: slice(8, None).indices(len(s))
Out[26]: (8, 19, 1)

编辑:使用 Eric 的改进,使用 None 而不是 len(s) 作为停止参数

关于Python - 获取切片索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335182/

相关文章:

python - 从 Python 中的响应中读取特定的 JSON 对象

python - 将 python 字符串转换为 numpy 数组

python - 如何让 Node Web 客户端与 Heroku 上的 REST API 对话?

python-2.7 - 命令 "python setup.py egg_info"失败,PATH/psycopg2 中的错误代码为 1

文件名中的 Python €

python - pretty-print JSON 转储

python - 拆分或替换 - 去掉两个字符串之间和周围的撇号和逗号

python - 在 Python 中使用多线程迭代字典

mysql - 如何将mysql数据库中的python时间戳转换为SQL查询中的日期

mysql - 无法在 Python 中导入 MySQLdb 模块