[Python] Python异常ValueError的问题

962 1
黑夜隐士 2022-11-6 09:47:40 | 显示全部楼层 |阅读模式
目录

    Python异常 ValueError规避方法规避方法:避免使用encoding关键字


Python异常 ValueError

ValueError: invalid literal for int() with base 10: '*'
试图将一个与数字无关的类型转化为整数,会抛出该异常。
  1. >>> int("99 years ago.")
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. ValueError: invalid literal for int() with base 10: '99 years ago.'
复制代码
规避方法:int函数参数应该合法使用。int函数使用传送门:Python中的int函数使用
ValueError: too many values to unpack (expected 2)
试图遍历字典时同时遍历键和值。
  1. >>> demo = {"China": "Beijing", "Japa": "Tokyo"}
  2. >>> for k, v in demo:
  3. ...   print(k, v)
  4. ...
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. ValueError: too many values to unpack (expected 2)
复制代码
Python只允许对字典key的遍历,因此上面的遍历方式是错误的。

规避方法

方法一:使用dict[key]的方式同时获取value
  1. >>> demo = {"China": "Beijing", "Japan": "Tokyo"}
  2. >>> for key in demo:
  3. ...   print(key, demo[key])
  4. ...
  5. China Beijing
  6. Japan Tokyo
复制代码
方法二:使用items方法
  1. >>> demo = {"China": "Beijing", "Japan": "Tokyo", "the United States": "Washington D.C."}
  2. >>> for key, value in demo.items():
  3. ...   print(key, value)
  4. ...
  5. China Beijing
  6. Japan Tokyo
  7. the United States Washington D.C.
  8. ValueError: binary mode doesn't take an encoding argument
复制代码
试图以二进制模式读取文件时指定编码方式。
  1. >>> with open("protoc-gen-go", "rb+", encoding="utf-8") as file:
  2. ...   data = file.read()
  3. ...
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. ValueError: binary mode doesn't take an encoding argument
复制代码
规避方法:避免使用encoding关键字
  1. >>> with open("protoc-gen-go", "rb+") as file:
  2. ...   data = file.read(10)
  3. ...
  4. >>> data
  5. b'\xcf\xfa\xed\xfe\x07\x00\x00\x01\x03\x00'
复制代码
以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行