我是python的新手,我必须创建一个打印用户输入字符串的中间字符的程序.这是我有的:
#accept string from user then print middle character
x = input("Enter a string: ")
print(x[len(x)/2-1])
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试运行该程序时,我不断收到此错误:
"TypeError:字符串索引必须是整数".
我不知道如何解决这个问题或如何让这个程序工作.请帮忙!
从你的错误我推断你使用python 3.
在python 3中,两个整数之间的除法返回一个浮点数:
>>> 3/2
1.5
>>> 4/2
2.0
Run Code Online (Sandbox Code Playgroud)
但是一个indeces必须是整数,所以你得到错误.要强制执行整数除法,必须使用//运算符:
>>> 3//2
1
>>> 4//2
2
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用math.ceil或者math.floor如果您想要更多控制浮动的圆角.