Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I slice a python string programmatically?

Tags:

python

string

Very simple question, hopefully. So, in Python you can split up strings using indices as follows:

>>> a="abcdefg"
>>> print a[2:4]
cd

but how do you do this if the indices are based on variables? E.g.

>>> j=2
>>> h=4
>>> print a[j,h]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: string indices must be integers
like image 824
Component 10 Avatar asked Jan 20 '26 15:01

Component 10


1 Answers

It works you just have a typo in there, use a[j:h] instead of a[j,h] :

>>> a="abcdefg"
>>> print a[2:4]
cd
>>> j=2
>>> h=4
>>> print a[j:h]
cd
>>> 
like image 83
bakkal Avatar answered Jan 22 '26 03:01

bakkal