![](/img/trans.png)
[英]How do I slice a string in python based on the text, not the letter number?
[英]How do I slice a python string programmatically?
希望很簡單的問題。 因此,在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
>>>
除了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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.