![](/img/trans.png)
[英]How do I remove the b'' prefix in a str variable with unicode escapes in python?
[英]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.