相关文章推荐

Pycharm提示: Expected type ‘optional[bytes]’ got ‘str’ instead

使用split类似函数的时候提示: Expected type ‘optional[bytes]’ got ‘str’ instead

row.split('\t')

Python

并不影响运行,但是如果强迫症的话,可以改用下面的形式:

row.split(b'\t')

Python

python字符串前面加u,r,b的含义

  • u/U:表示unicode字符串,代表是对字符串进行unicode编码
  • r/R:非转义的原始字符串,转义字符不生效,常用于正则表达式
  • b:bytes,python3.x里默认的str是(py2.x里的)unicode, bytes是(py2.x)的str, b
b'\xe2\x82\xac20'.decode('utf-8')  # byte 转 Unicode 字符串
# €20 对应 b'\xe2\x82\xac20'
'€20'.encode('utf-8')   # unicode 字符串转 byte

Python

Python字典读取 KeyError

在Python中,使用下标访问字典元素时,如果不知道是否存在 Key ,使用get代替,而且下标的字符串编码要一致,否则读不到数据。

dict = {'0':0, '1':1}
print(dict['3')   # 报错
print(dict.get('3')  # None
print(dict[0])  # 报错
print(dict.get(b'0')) #None

Python

Python3 字符串类型 str 和字节类型字符串 b”互转

当提示错误:TypeError: must be str, not bytes,或者:TypeError: must be bytes, not str 时,需要对字符串进行转换:

str = 'str test'
bytes = b'byte test'
# str -> bytes
str.encode()
# bytes -> str
bytes.decode()

Python

Python 字符串列表转为数字列表

当从文件中导入数据的时候,读取的是字符串,有时候我们需要把字符串进行分割,分割生存的列表是字符串数组,需要转化为数值数组。

str = '3,4,5,6'
record_list = str.split(',')  # 此时得到的是:['3','4','5','6']
# 使用循环来进行转换
record_list = [int(x) for x in numbers]
# 使用map函数,用于Python2
record_list = map(int, record_list)
# 在Python3中使用map函数得到的是map对象,还需要转为list
record_list = list(map(int, record_list))
# 上面的 int 参数为转换的类型,还可以是float等
record_list = list(map(eval, record_list))
原文链接:https://uusama.com/395.html Pycharm提示:Expectedtype‘optional[bytes]’ got ‘str’ instead使用split类似函数的时候提示:Expectedtype‘optional[bytes]’ got ‘str’ insteadrow.split('\t')并不影响运行,但是如果强迫症的话,可以改用下面的形式:row.split(b'\t')python字符串前面加u,r,b... 记录一次报错 expected type ‘Optional[dtype]’, got ‘Type[float]’ instead 遇到这种情况一般都是类型不对了,要根据提示更改类型,比如这里我们看到 expected type 'Optional[dtype]', got 'Type[float]' 其实就是希望得到ptional[dtype]这个类型,但是给了Type[float]这个类型 更改过来就行了 本篇文章就是记录一些在学习Python过程中出现的一些错误与修改方法,在你不知道是什么错误时,不妨进来看看这些千奇百怪的报错,说不定其中就有你的那一个呢,解决!!! 本篇文章实时更新,收藏不亏!!! 1、End of statement expected 这个意思是:预计报表结束,即输出这里没加括号 解决:使用括号把输出内容括起来 2、Remove redundant parentheses 这个意思是:删除多余的括号 解决:删掉外面括号即可
 
推荐文章