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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With