简体   繁体   English

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

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

Adding the prefix "b" to a string converts it to bytes: 将字符“b”添加到字符串会将其转换为字节:

b'example'

But I can't figure out how to do this with a variable. 但我无法弄清楚如何用变量做到这一点。 Assuming string = 'example' , none of these seem to work: 假设string = 'example' ,这些似乎都不起作用:

b(string)
b string
b'' + string

Is there a simple way to do this? 有一个简单的方法吗?

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

In Python3: 在Python3中:

Bytes literals are always prefixed with 'b' or 'B'; 字节文字总是以'b'或'B'为前缀; they produce an instance of the bytes type instead of the str type. 它们生成字节类型的实例而不是str类型。 They may only contain ASCII characters; 它们可能只包含ASCII字符; bytes with a numeric value of 128 or greater must be expressed with escapes. 数字值为128或更大的字节必须用转义表示。

In Python2: 在Python2中:

A prefix of 'b' or 'B' is ignored in Python 2; Python 2中忽略前缀'b'或'B'; it indicates that the literal should become a bytes literal in Python 3. 它表明文字应该成为Python 3中的字节文字。

More about bytes(): 有关bytes()的更多信息:

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

Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior. 返回一个新的“bytes”对象,它是0 <= x <256范围内的不可变整数序列。字节是bytearray的不可变版本 - 它具有相同的非变异方法和相同的索引和切片行为。

Accordingly, constructor arguments are interpreted as for bytearray(). 因此,构造函数参数被解释为bytearray()。

Bytes objects can also be created with literals, see String and Bytes literals. 也可以使用文字创建字节对象,请参阅字符串和字节文字。

Use bytes() : 使用bytes()

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

其中'string'是你的变量。

Or use the bytes.decode() method to convert to string (using a given encoding): 或者使用bytes.decode()方法转换为string (使用给定的编码):

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

The opposite conversion is str.encode() to convert a string to bytes : 相反的转换是str.encode()string转换为bytes

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

I have checked for this for long time and i think the best way to convert a string into a varible is using vars() 我已经检查了很长时间,我认为将字符串转换为变量的最佳方法是使用vars()

vars()['variable name'] = value to assign 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