繁体   English   中英

在python变量中添加“b”前缀?

[英]Add “b” prefix to python variable?

将字符“b”添加到字符串会将其转换为字节:

b'example'

但我无法弄清楚如何用变量做到这一点。 假设string = 'example' ,这些似乎都不起作用:

b(string)
b string
b'' + string

有一个简单的方法吗?

# only an example, you can choose a different encoding
bytes('example', encoding='utf-8')

在Python3中:

字节文字总是以'b'或'B'为前缀; 它们生成字节类型的实例而不是str类型。 它们可能只包含ASCII字符; 数字值为128或更大的字节必须用转义表示。

在Python2中:

Python 2中忽略前缀'b'或'B'; 它表明文字应该成为Python 3中的字节文字。

有关bytes()的更多信息:

bytes([source [,encoding [,errors]]])

返回一个新的“bytes”对象,它是0 <= x <256范围内的不可变整数序列。字节是bytearray的不可变版本 - 它具有相同的非变异方法和相同的索引和切片行为。

因此,构造函数参数被解释为bytearray()。

也可以使用文字创建字节对象,请参阅字符串和字节文字。

使用bytes()

>>> bytes("hello", encoding="ascii")
b'hello'
string = bytes(string, encoding= 'utf-8')

其中'string'是你的变量。

或者使用bytes.decode()方法转换为string (使用给定的编码):

>>> b'hello'.decode('utf-8')
'hello'

相反的转换是str.encode()string转换为bytes

>>> 'hello'.encode('utf-8')
b'hello'

我已经检查了很长时间,我认为将字符串转换为变量的最佳方法是使用vars()

vars()['variable name'] =要分配的值

vars()['created_variable'] = 1
print(created_variable)
>> 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM