如何以编程方式切片python字符串?

Com*_* 10 1 python string

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

>>> a="abcdefg"
>>> print a[2:4]
cd
Run Code Online (Sandbox Code Playgroud)

但如果指数基于变量,你如何做到这一点?例如

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

bak*_*kal 10

它只是在那里有一个拼写错误,使用a[j:h]而不是a[j,h] :

>>> a="abcdefg"
>>> print a[2:4]
cd
>>> j=2
>>> h=4
>>> print a[j:h]
cd
>>> 
Run Code Online (Sandbox Code Playgroud)


Oli*_*ier 5

除了 Bakkal 的回答,这里是如何以编程方式操作切片,这有时很方便:

a = 'abcdefg'
j=2;h=4
my_slice = slice(j,h) # you can pass this object around if you wish

a[my_slice] # -> cd
Run Code Online (Sandbox Code Playgroud)