将字符串转换为int?

jam*_*myn 1 python string int

在一个猜信游戏上工作.

为什么在下面的示例中,当我将变量的值"userGuessPosition"硬编码为2时,代码按预期工作.

secretWord = ('music')
userGuessPosition = 2 
slice1 = (secretWord.__len__()) - userGuessPosition - 1  
print (secretWord[slice1:userGuessPosition])
Run Code Online (Sandbox Code Playgroud)

但是当我依赖input()函数并在提示符下键入2时,没有任何反应?

secretWord = ('music')
userGuessPosition = 0
userGuessPosition == input()
slice1 = (secretWord.__len__()) - userGuessPosition - 1  
print (secretWord[slice1:userGuessPosition])
Run Code Online (Sandbox Code Playgroud)

我认为这是因为我的键盘输入"2"被视为字符串而不是整数.如果是这种情况,那么我不清楚转换它的正确语法.

val*_*ron 5

userGuessPosition = int(input())
Run Code Online (Sandbox Code Playgroud)

(Single =int将字符串转换为 int)


Ron*_*ael 5

问题不在于输入被识别为字符串,而是在语法中:您正在进行比较操作,您应该在其中执行赋值操作.

你必须使用

userGuessPosition = input()
Run Code Online (Sandbox Code Playgroud)

代替

userGuessPosition == input()
Run Code Online (Sandbox Code Playgroud)

input()函数实际上确实将输入数转换为最合适的类型,sp应该不是问题.但是,如果您需要将字符串(例如my_string)转换为整数,那么您需要做的就是my_int = int(my_string).

编辑

正如下面@HenryKeiter所提到的,根据你的Python版本,你实际上可能需要input()手动将返回值转换为整数,因为raw_input()(它总是将输入作为字符串输入)input()在Python 3中被重命名.