将字符串转换为负数 [英] Convert string to negative number

查看:45
本文介绍了将字符串转换为负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串类型转换为数字

list = ["-5","4","-3","variable"] # 输入list = [-5,4,-3,"variable"] # 预期输出

我在转换负数时遇到问题

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

<块引用>

ValueError: 以 10 为基数的 int() 的无效文字:'-5'

解决方案

实际上,我无法重现您的错误,它仅适用于 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.

这篇关于将字符串转换为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆