2010-05-27 23 views
1

很簡單的問題,希望。所以,在Python中可以分割使用指標如下字符串:如何以編程方式分割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 
+3

使用冒號而不是逗號......就像使用數字索引一樣。 :o) – 2010-05-27 11:15:32

回答

3

除了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 
+0

不錯!非常感謝。 – 2010-05-27 11:45:35

10

它的工作原理,你只是有一個錯字在那裏,使用a[j:h]代替a[j,h]

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

Doh!謝謝! – 2010-05-27 11:28:26