2

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
1
  • 3
    Use a colon, not a comma ... just like you would with numerical indices. :o) Commented May 27, 2010 at 11:15

2 Answers 2

12

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
>>> 
Sign up to request clarification or add additional context in comments.

Comments

5

In addition to Bakkal's answer, here is how to manipulate slices programmatically, which is sometimes convenient:

a = 'abcdefg'
j=2;h=4
my_slice = slice(j,h) # you can pass this object around if you wish

a[my_slice] # -> cd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.