如何通过编程方式切片 Python 字符串?

2 投票
2 回答
5029 浏览
提问于 2025-04-15 23:14

这是个很简单的问题,希望能帮到你。在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

2 个回答

12

这个代码是可以工作的,只是你那里有个拼写错误。应该用 a[j:h] 而不是 a[j,h]

>>> a="abcdefg"
>>> print a[2:4]
cd
>>> j=2
>>> h=4
>>> print a[j:h]
cd
>>> 
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

撰写回答