-1

When trying to print the middle character of a string using the following code:

def mid(a):
    return a[(len(a) + 1) / 2]
    
print(mid("abc"))

I get the error:

TypeError: string indices must be integers

Changing it to:

 def mid(a):
    return a[(len(a) - 1) // 2 : (len(a) + 2) // 2]
    
print(mid("abc"))

outputs:

b

Why does directly grabbing the middle value return the TypeError, but grabbing the 0th value and then the middle value actually work?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Leprekus
  • 34
  • 6

1 Answers1

2

Division returns a float. You want floor division.

>>> 4/2
2.0
>>> 4//2
2

It seems like you fixed this without noticing in your changed code.

wjandrea
  • 28,235
  • 9
  • 60
  • 81