Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: Getting TypeError: Slices must be integers... But they are I believe

I am trying to write a function called "middle" that takes the middle 3 digits of odd numbers, or the middle 4 digits of even numbers. If the number is less than 5 digits, it just returns the whole number. Here is my work:

def middle(x):
    mystring=str(x)
    length=len(mystring)
    if len(mystring)<=5:
        return(x)
    elif len(mystring)%2==0:
        return (mystring[((length/2)-1):((length/2)+3)])
    else:
        return (mystring[(length//2):((length//2)+3)])
middle (1234567890)

I keep getting "type error: slice indices must be integers or none or have an_index_method" and I don't understand.

like image 563
JackD Avatar asked Dec 11 '22 21:12

JackD


1 Answers

You're using Python 3, I bet. [And you are -- I just noticed the tag this second.] length/2 will be a float:

    return (mystring[((length/2)-1):((length/2)+3)])

use length//2 throughout instead.

Note this will happen even if length is even:

>>> s = 'abcd'
>>> len(s)
4
>>> len(s)/2
2.0
>>> s[len(s)/2:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
>>> s[len(s)//2:]
'cd'
like image 156
DSM Avatar answered Apr 20 '23 00:04

DSM