>> print a[2:4] cd 但是如果索引是基于变量的,你如何做到这一点-6ren">
gpt4 book ai didi

python - 如何以编程方式对 python 字符串进行切片?

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:20 25 4
gpt4 key购买 nike

很简单的问题,希望。因此,在 Python 中,您可以使用索引拆分字符串,如下所示:

>>> a="abcdefg"
>>> print a[2:4]
cd

但是如果索引是基于变量的,你如何做到这一点呢?例如

>>> j=2
>>> h=4
>>> print a[j,h]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: string indices must be integers

最佳答案

它的工作原理你只是有一个错字,使用 a[j:h] 而不是 a[j,h] :

>>> a="abcdefg"
>>> print a[2:4]
cd
>>> j=2
>>> h=4
>>> print a[j:h]
cd
>>>

关于python - 如何以编程方式对 python 字符串进行切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2920551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com