python中bytes用法_Python bytes()用法及代码示例

python语言轻松提供了不同数据类型之间的相互转换。本文旨在演示和工作到bytes()的不同数据类型的相互转换,通常可用于编码方案。

byte()将对象转换为给定大小和数据的不可变字节表示的对象。

语法:bytes(src,enc,err)参数:src:必须转换的源对象enc:如果对象是字符串,则需要的编码err:如果字符串转换失败,则处理错误的方式。返回:根据src类型,由unicode 0-256个字符组成的字节不可变对象。整数:返回大小初始化为null的大小的数组。可迭代:返回元素大小等于可迭代元素(0-256)的可迭代大小的数组。字符串:返回已编码的字符串acc。编码,如果编码失败,则根据指定的err执行操作。无参数:返回大小为0的数组。

代码1:在整数,无和可迭代对象上演示byte()

# Python 3 code to demonstrate the

# working of bytes() on int, iterables, none

# initializing integer and iterables

a = 4

lis1 = [1, 2, 3, 4, 5]

# No argument case

print ("Byte conversion with no arguments:" + str(bytes()))

# conversion to bytes

print ("The integer conversion results in:"  + str(bytes(a)))

print ("The iterable conversion results in:"  + str(bytes(lis1)))

输出:

Byte conversion with no arguments:b''

The integer conversion results in:b'\x00\x00\x00\x00'

The iterable conversion results in:b'\x01\x02\x03\x04\x05'

字节与字符串的行为

字节接受字符串作为参数,并要求使用编码方案来执行它。其中最重要的方面是在编码失败的情况下处理错误,其中定义的一些错误处理方案为:

String Error Handlers:

strict: Raises the default UnicodeDecodeError in case of encode failure.

ignore: Ignores the unencodable character and encodes the remaining string.

replace: Replaces the unencodable character with a ‘?’.

代码2:使用字符串演示bytes()

# Python 3 code to demonstrate the

# working of bytes() on string

# initializing string

str1 = 'GeeksfÖrGeeks'

# Giving ascii encoding and ignore error

print ("Byte conversion with ignore error:" +

str(bytes(str1, 'ascii', errors = 'ignore')))

# Giving ascii encoding and replace error

print ("Byte conversion with replace error:" +

str(bytes(str1, 'ascii', errors = 'replace')))

# Giving ascii encoding and strict error

# throws exception

print ("Byte conversion with strict error:" +

str(bytes(str1, 'ascii', errors = 'strict')))

输出:

Byte conversion with ignore error:b'GeeksfrGeeks'

Byte conversion with replace error:b'Geeksf?rGeeks'

异常:

Traceback (most recent call last):

File "/home/0458f7fae57c6f4102366356593842ef.py", line 15, in

print ("Byte conversion with strict error:" + str(bytes(str1, 'ascii', errors = 'strict')))

UnicodeEncodeError:'ascii' codec can't encode character '\xd6' in position 6:ordinal not in range(128)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值