向python变量添加“b”前缀?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19511440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:56:22  来源:igfitidea点击:

Add "b" prefix to python variable?

pythonpython-3.xbyte

提问by zombio

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?

有没有一种简单的方法可以做到这一点?

采纳答案by Leonardo.Z

# 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'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

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

In Python2:

在 Python2 中:

A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3.

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

More about bytes():

有关 bytes() 的更多信息:

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.

Accordingly, constructor arguments are interpreted as for bytearray().

Bytes objects can also be created with literals, see String and Bytes literals.

字节([源[,编码[,错误]]])

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

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

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

回答by Tim Pietzcker

Use bytes():

使用bytes()

>>> bytes("hello", encoding="ascii")
b'hello'

回答by a_r

string = bytes(string, encoding= 'utf-8')

where 'string' is your variable.

其中“字符串”是您的变量。

回答by Simon G.

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 stringto bytes:

相反的转换是str.encode()将 a 转换stringbytes

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

回答by saias

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()['变量名'] = 要分配的值

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