5

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.

1
  • Also reproducible on Python 2.7 with from __future__ import division; without that future statement it works.
    – user9876
    Oct 15, 2012 at 1:58

2 Answers 2

14

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'
4
  • Well I only use the single slash for when the integer is even so I don't think its that. I tried it anyway, and when I ran it, it started freaking out (I'm using pyscripter)... the red text started flowing in the interpreter and every few lines it says "stream has been closed" Ehhh... It won't stop now
    – JackD
    Oct 15, 2012 at 1:59
  • Sounds like that fixed it and you discovered the next bug :-)
    – user9876
    Oct 15, 2012 at 2:00
  • I quit the program then restarted, it works fine now. Thanks mate. (for now :P)
    – JackD
    Oct 15, 2012 at 2:02
  • 1
    +1. The 4/2 returns 2.0 in Python 3. The / always returns float. (The rule of least surprise back again in this case for Python 3.)
    – pepr
    Oct 15, 2012 at 6:13
0

The // operator only returns an int when the numerator is an int, while it still returns a float when the numerator is a float.

assert type(2//2) == int
assert type(2.//2) == float

To overcome this limitation in slices, the following function might be used:

def intslice(*args, **kwargs):
    '''Return a slice object that has integer boundaries.

    Example:
    np.arange(10)[intslice(10/10,10/2)]
    '''

    args = [int(arg) for arg in args]
    kwargs = {key: int(arg) for key, arg in kwargs.items()}
    return slice(*args, **kwargs)

Now intslice(10/10,10/2) returns slice(1,5)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.