Skip to main content
 首页 » 编程设计

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

2025年05月04日13del

很简单的问题,希望。因此,在 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 
>>>