zoukankan      html  css  js  c++  java
  • python之base64编码出现b的问题(转)

    写代码过程中发现,用base64编码后会带有b,这会影响到请求结果,该如何清除b呢?

     下面来看一下实际的演示代码:

    import base64
    
    before_base64 = 'abc'.encode()
    after_base64 = base64.b64encode(before_base64)
    print(after_base64)

    运行结果如下:abc用base64编码后应该是YWJj,但是实际上却不只这些,这个b应该是用来区分base64编码和字符串吧,所以如果想单纯的使用base64编码就得把多余的字符去掉。

    b'YWJj'

    下面列举几种解决办法:

    1. decode为utf-8编码:

    import base64
    
    before_base64 = 'abc'.encode()
    after_base64 = base64.b64encode(before_base64)
    print(after_base64)
    
    right_base64 = after_base64.decode('utf-8')
    print(right_base64)

    2. str转化为utf-8编码;

    import base64
    
    before_base64 = 'abc'.encode()
    after_base64 = base64.b64encode(before_base64)
    print(after_base64)
    
    right_base64 = str(after_base64, 'utf-8')
    print(right_base64)

    3. decode为ASCII编码

    import base64
    
    before_base64 = 'abc'.encode()
    after_base64 = base64.b64encode(before_base64)
    print(after_base64)
    
    right_base64 = str(after_base64, 'utf-8')
    print(right_base64)

    运行结果都是;

    b'YWJj'
    YWJj

    这样就可以获得纯净的base64编码了!

    转:https://zhuanlan.zhihu.com/p/180470369

  • 相关阅读:
    C#的list和arry相互转化
    c++11の的左值、右值以及move,foward
    c++11の异步方法 及线程间通信
    C#的static
    HDU4027 Can you answer these queries?
    POJ3264 Balances Lineup
    ZOJ1610 Count the Colors
    ZOJ4110 Strings in the Pocket(2019浙江省赛)
    HDU1698 Just a Hook
    POJ3468 A Simple Problem with Integers
  • 原文地址:https://www.cnblogs.com/annatest/p/14758317.html
Copyright © 2011-2022 走看看