2

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.

2
  • It works for me with an arbitrary integer. I feel like you have a float accidentally. Commented Jun 26, 2017 at 17:01
  • 2
    Show us how you initialized halflength. It does not seem to be an integer. Commented Jun 26, 2017 at 17:01

3 Answers 3

4

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

Comments

2

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.

Comments

0

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)::]

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.