如何在python中将文本编码为base64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23164058/
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
How to encode text to base64 in python
提问by sukhvir
I am trying to encode a text string to base64.
我正在尝试将文本字符串编码为 base64。
i tried doing this :
我试过这样做:
name = "your name"
print('encoding %s in base64 yields = %s\n'%(name,name.encode('base64','strict')))
But this gives me the following error:
但这给了我以下错误:
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
How do I go about doing this ? ( using Python 3.4)
我该怎么做?(使用 Python 3.4)
采纳答案by Alexander Ejbekov
Remember to import base64 and that b64encode takes bytes as an argument.
请记住导入 base64 并且 b64encode 将字节作为参数。
import base64
base64.b64encode(bytes('your string', 'utf-8'))
回答by mgilson
It turns out that this is important enough to get it's own module...
事实证明,这对于获得自己的模块非常重要......
import base64
base64.b64encode(b'your name') # b'eW91ciBuYW1l'
base64.b64encode('your name'.encode('ascii')) # b'eW91ciBuYW1l'
回答by Tagar
1) This works without imports in Python 2:
1) 这在 Python 2 中无需导入即可工作:
>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>
(although this doesn't work in Python3 )
(虽然这在 Python3 中不起作用)
2) In Python 3 you'd have to import base64 and do base64.b64decode('...') - will work in Python 2 too.
2) 在 Python 3 中,您必须导入 base64 并执行 base64.b64decode('...') - 也可以在 Python 2 中使用。
回答by NewBee
To compatibility with both py2 and py3
兼容py2和py3
import six
import base64
def b64encode(source):
if six.PY3:
source = source.encode('utf-8')
content = base64.b64encode(source).decode('utf-8')
回答by ujjawal sharma
Use the below code:
使用以下代码:
import base64
#Taking input through the terminal.
welcomeInput= raw_input("Enter 1 to convert String to Base64, 2 to convert Base64 to String: ")
if(int(welcomeInput)==1 or int(welcomeInput)==2):
#Code to Convert String to Base 64.
if int(welcomeInput)==1:
inputString= raw_input("Enter the String to be converted to Base64:")
base64Value = base64.b64encode(inputString.encode())
print "Base64 Value = " + base64Value
#Code to Convert Base 64 to String.
elif int(welcomeInput)==2:
inputString= raw_input("Enter the Base64 value to be converted to String:")
stringValue = base64.b64decode(inputString).decode('utf-8')
print "Base64 Value = " + stringValue
else:
print "Please enter a valid value."
回答by TomDotTom
Whilst you can of course use the base64
module, you can also to use the codecs
module (referred to in your error message) for binary encodings (meaning non-standard & non-text encodings).
虽然您当然可以使用该base64
模块,但您也可以使用该codecs
模块(在您的错误消息中提到)进行二进制编码(意味着非标准和非文本编码)。
For example:
例如:
import codecs
my_bytes = b"Hello World!"
codecs.encode(my_bytes, "base64")
codecs.encode(my_bytes, "hex")
codecs.encode(my_bytes, "zip")
codecs.encode(my_bytes, "bz2")
This can come in useful for large data as you can chain them to get compressed and json-serializable values:
这对于大数据很有用,因为您可以将它们链接起来以获得压缩和 json 可序列化的值:
my_large_bytes = my_bytes * 10000
codecs.decode(
codecs.encode(
codecs.encode(
my_large_bytes,
"zip"
),
"base64"),
"utf8"
)
Refs:
参考:
回答by Hafiz Hashim
It looks it's essential to call decode() function to make use of actual string data even after calling base64.b64decode over base64 encoded string. Because never forget it always return bytes literals.
即使在通过 base64 编码的字符串调用 base64.b64decode 之后,调用 decode() 函数来使用实际的字符串数据看起来也很重要。因为永远不要忘记它总是返回字节文字。
import base64
conv_bytes = bytes('your string', 'utf-8')
print(conv_bytes) # b'your string'
encoded_str = base64.b64encode(conv_bytes)
print(encoded_str) # b'eW91ciBzdHJpbmc='
print(base64.b64decode(encoded_str)) # b'your string'
print(base64.b64decode(encoded_str).decode()) # your string
回答by CONvid19
For py3, base64 encode
and decode
string:
对于 py3、base64encode
和decode
字符串:
import base64
def b64e(s):
return base64.b64encode(s.encode()).decode()
def b64d(s):
return base64.b64decode(s).decode()