0

I am relatively new to python and I have to create a program that prints the middle character of a user-inputted string. Here is what I have:

#accept string from user then print middle character

x = input("Enter a string: ")
print(x[len(x)/2-1])

However I keep getting this error when I try to run the program:

"TypeError: string indices must be integers".

Im not sure how to fix this or how to get this program to work. Please help!

Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
Jordan Jackson
  • 9
  • 1
  • 2
  • 5

2 Answers2

4

From your error I infer that you are using python 3.

In python 3 division between two integers returns a float:

>>> 3/2
1.5
>>> 4/2
2.0

But a indeces must be integers, so you get the error. To force an integer division you must use the // operator:

>>> 3//2
1
>>> 4//2
2

Alternatively you can use math.ceil or math.floor if you want more control on the rounding of the floats.

Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
0

This is a way:

x = raw_input("Enter a string: " )
print (x[:len(x)//2])
imerso
  • 511
  • 4
  • 12