欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python異常?ValueError的問題

 更新時(shí)間:2022年11月03日 09:52:22   作者:TCatTime  
這篇文章主要介紹了Python異常?ValueError的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Python異常 ValueError

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

試圖將一個(gè)與數(shù)字無關(guān)的類型轉(zhuǎn)化為整數(shù),會(huì)拋出該異常。

>>> int("99 years ago.")
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '99 years ago.'

規(guī)避方法:int函數(shù)參數(shù)應(yīng)該合法使用。int函數(shù)使用傳送門:Python中的int函數(shù)使用

ValueError: too many values to unpack (expected 2)

試圖遍歷字典時(shí)同時(shí)遍歷鍵和值。

>>> demo = {"China": "Beijing", "Japan": "Tokyo"}
>>> for k, v in demo:
... ? ? print(k, v)
...
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

Python只允許對字典key的遍歷,因此上面的遍歷方式是錯(cuò)誤的。

規(guī)避方法

方法一:使用dict[key]的方式同時(shí)獲取value

>>> demo = {"China": "Beijing", "Japan": "Tokyo"}
>>> for key in demo:
... ? ? print(key, demo[key])
...
China Beijing
Japan Tokyo

方法二:使用items方法

>>> demo = {"China": "Beijing", "Japan": "Tokyo", "the United States": "Washington D.C."}
>>> for key, value in demo.items():
... ? ? print(key, value)
...
China Beijing
Japan Tokyo
the United States Washington D.C.
ValueError: binary mode doesn't take an encoding argument

試圖以二進(jìn)制模式讀取文件時(shí)指定編碼方式。

>>> with open("protoc-gen-go", "rb+", encoding="utf-8") as file:
... ? ? data = file.read()
...
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
ValueError: binary mode doesn't take an encoding argument

規(guī)避方法:避免使用encoding關(guān)鍵字

>>> with open("protoc-gen-go", "rb+") as file:
... ? ? data = file.read(10)
...
>>> data
b'\xcf\xfa\xed\xfe\x07\x00\x00\x01\x03\x00'

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python 為什么推薦蛇形命名法原因淺析

    Python 為什么推薦蛇形命名法原因淺析

    這篇文章主要介紹了Python 為什么推薦蛇形命名法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-06-06
  • 理解Python中的類與實(shí)例

    理解Python中的類與實(shí)例

    這篇文章主要介紹了Python中的類與實(shí)例,類與實(shí)例的概念是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-04-04
  • 最新評論