2010-05-27 22 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