a = b'h\x6511o'
print(list(a))
print(a)
a = 'a\\u300 propos'
print(list(a))
print(a)
#输出结果
[104, 101, 49, 49, 111]
b'he11o'['a', '\\', 'u', '3', '0', '0', ' ', 'p', 'r', 'o', 'p', 'o', 's']
a\u300 propos
该问题等价于:使用 bytes 和 str 时需要注意的两个问题
#bytes+bytes
print(b'a' + b'1')
#str+str
print('b' + '2')
#输出结果
b'a1'b2
#bytes+str
print('c' + b'2')
#输出结果
print('c' + b'2')
TypeError: can only concatenate str (not "bytes") to str
assert b'c' > b'a'
assert 'c' > 'a'
但 bytes 和 str 之间用二元操作符也会报错
assert b'c' > 'a'
#输出结果
assert b'c' > 'a'TypeError: '>' not supported between instances of 'bytes' and 'str'
两个类型的实例相比较总会为 False,即使字符完全相同
#判断 str、bytes
print('a' == b'a')
#输出结果
False
两种类型的实例都可以出现在 % 操作符的右侧,用来替换左侧那个格式字符串(format string)里面的%s
但是!如果格式字符串是 bytes 类型,那么不能用 str 实例来替换其中的 %s,因为 Python 不知道这个 str 应该按照什么字符集来编码
#%
print(b'red %s' % 'blue')
#输出结果
print(b'red %s' % 'blue')
TypeError: %b requires a bytes-like object, or an object that implements __bytes__, not 'str'
但是!反过来却可以,如果格式字符串是 str 类型,则可以用bytes 实例来替换其中的 %s,但结果可能不是预期结果
#%
print('red %s' % b'blue')
#输出结果
red b'blue'
不能使用原始的 bytes
#写入二进制数据
with open('test.txt', "w+") as f:
f.write(b"\xf1\xf2")
#输出结果
f.write(b"\xf1\xf2")
TypeError: write() argument must be str, not bytes
with open('test.txt', "wb") as f:
f.write(b"\xf1\xf2")
with open('test.txt', "r+") as f:
f.read()
#输出结果
(result, consumed) =self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 0: invalid continuation byte
with open('test.txt', "rb") as f:
print(b"\xf1\xf2" ==f.read())
#输出结果
True
with open('test.txt', "r", encoding="cp1252") as f:
print(f.read())
#输出结果
ñò
这样也不会有异常了
需要注意当前操作系统默认的字符集编码
https://www.cnblogs.com/poloyy/p/15536156.html
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.cnblogs.com/poloyy/p/15549664.html
内容来源于网络,如有侵权,请联系作者删除!