Python 将字符串类型转换为 int 失败
Python typecasting string to int fails
当我尝试在 python (2.7) 中进行从字符串到整数的简单类型转换时出现错误:
year = device.time[year_pos:].strip() # This is '1993'
t = int(year) # Throws exception: "UnboundLocalError: local variable 'int' referenced before assignment"
为什么? :)
UnboundLocalError
听起来好像您在代码的其他范围内为名称 int
分配了一些东西(即抛出异常的代码在函数内部,并且您'我们使用 int
作为名称来在全局代码或其他地方存储变量)。有 a blog post about UnboundLocalError
在那里你可以阅读更多关于此类问题的信息,但对于你的问题,我只是建议不要使用内置名称来存储变量。
当我尝试在 python (2.7) 中进行从字符串到整数的简单类型转换时出现错误:
year = device.time[year_pos:].strip() # This is '1993'
t = int(year) # Throws exception: "UnboundLocalError: local variable 'int' referenced before assignment"
为什么? :)
UnboundLocalError
听起来好像您在代码的其他范围内为名称 int
分配了一些东西(即抛出异常的代码在函数内部,并且您'我们使用 int
作为名称来在全局代码或其他地方存储变量)。有 a blog post about UnboundLocalError
在那里你可以阅读更多关于此类问题的信息,但对于你的问题,我只是建议不要使用内置名称来存储变量。