首页 > 编程语言 >Python 报错:int() can't convert non-string with explicit base

Python 报错:int() can't convert non-string with explicit base

时间:2022-09-02 18:59:56浏览次数:76  
标签:10 convert string int non base 报错 进制

背景

今天python操作二进制然后报错,记录一下

>>> int(101,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
>>> 

问题原因

int() 其实是一个类

class int(x, base=10)

x -- 字符串或数字。
base -- 进制数,默认十进制。

调用int

>>> int('5')   # 等价于int('5',10),将字符串5,转化成10进制int
5
>>> int(5)  # int(5,10)  将数字5 转化成10进制int
5
>>> int('5',2)  # 代表字符串'5' 为2进制,转化成10进制,但是二进制中只有0和1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '5'
>>> int('5',10)
5
>>> int(5,2)    # 其实需要注意的是,除了十进制是数字以外,python中其他的进制都是字符串
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
>>> int('101',2)
5
>>> type(bin(5))
<class 'str'>
>>> type(hex(5))
<class 'str'>
>>>

解决办法

如果传base,那么第一个参数一定修改成字符串格式

>>> int('101',2)
5

标签:10,convert,string,int,non,base,报错,进制
From: https://www.cnblogs.com/tarzen213/p/16650934.html

相关文章