How to encode text to base64 in python

前端 未结 8 2113
悲&欢浪女
悲&欢浪女 2020-12-24 01:17

I am trying to encode a text string to base64.

i tried doing this :

name = \"your name\"
print(\'encoding %s in base64 yields = %s\\n\'%(name,name.en         


        
相关标签:
8条回答
  • 2020-12-24 01:43

    Remember to import base64 and that b64encode takes bytes as an argument.

    import base64
    base64.b64encode(bytes('your string', 'utf-8'))
    
    0 讨论(0)
  • 2020-12-24 01:47

    1) This works without imports in 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 )

    2) In Python 3 you'd have to import base64 and do base64.b64decode('...') - will work in Python 2 too.

    0 讨论(0)
提交回复
热议问题