Sumtinlazy
Sumtinlazy

Reputation: 347

Using variables as slice indices for python

For a class I am learning how to slice integers. In the code below the variable halflength is equal to half of the length of the variable message.

new = message[halflength::]

halflength is equal to an integer, however whenever I run this code I get this error:

TypeError: slice indices must be integers or None or have an __index__ method

Basically I need to try and create a new string that is equal to the second half of the original string.

Example: original string 1234 would produce 34 as the new string.

Upvotes: 2

Views: 2876

Answers (3)

kurian
kurian

Reputation: 189

Make sure halflength is of type Integer. You can use "isinstance" method to verify.

# python
 Python 2.7.5 (default, Aug  2 2016, 04:20:16 
 >>> halflength = "4"
 >>> isinstance(halflength,int)`
 False`
 >>> halflength=4
 >>> isinstance(halflength,int)
 True
 >>>

Try This:

message[int(halflength)::]

Upvotes: 0

Buzz
Buzz

Reputation: 1907

to do what you want to do try something like this:

halfLength=len(message)//2
newMessage=message[halfLength::]

if you get the length this way it will always be an integer that you can then use to get parts of stings with.

Upvotes: 2

Igor Yudin
Igor Yudin

Reputation: 403

I think the problem is you get a float type for halfLength after division, try to cast it to int, or use integer division

halfLength = int(halfLength)

or

halfLength = len(message) // 2

Upvotes: 4

Related Questions