Check if a string is encoded in base64 using Python

前端 未结 10 2045
离开以前
离开以前 2021-02-05 01:56

Is there a good way to check if a string is encoded in base64 using Python?

10条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 02:18

    x = 'possibly base64 encoded string'
    result = x
    try:
       decoded = x.decode('base64', 'strict')
       if x == decoded.encode('base64').strip():
           result = decoded
    except:
       pass
    

    this code put in the result variable decoded string if x is really encoded, and just x if not. Just try to decode doesn't always work.

提交回复
热议问题