且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串转换为负数

更新时间:2023-02-09 19:47:39

实际上,我无法重现您的错误,它仅适用于 python 2.7.13

>>>int("-5")>>>-5

在 python 3.4 中

所以,可能是python版本问题,我建议更新您的 python 版本,通过从 站点 重新安装较新的版本,它将完美地替换它(软件包未受影响), 除非您使用的是 anaconda 之类的特殊发行版 ..

用于处理您的列表(混合字符和数字)使用:

尝试:除了:声明.

I need to convert from string type to a number

list = ["-5","4","-3","variable"]  # Input

list = [-5,4,-3,"variable"]        # epected output

I have a problem when converting the negative number

list[0]=int(list[0])

ValueError: invalid literal for int() with base 10: '-5'

Actually, I cannot reproduce your error , it just work in python 2.7.13

>>>int("-5")
>>> -5

and in python 3.4

so, it could be a python version problem , I recommend updating your python version , by reinstalling the newer , from the site , it will replace it perfectly ( packages untouched ) , unless you are using , a special distribution like anaconda ..

for processing your list ( mixed chars and numbers ) use:

try: except: statement.