Check if a string is encoded in base64 using Python

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

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

10条回答
  •  萌比男神i
    2021-02-05 02:16

    The solution I used is based on one of the prior answers, but uses more up to date calls.

    In my code, the my_image_string is either the image data itself in raw form or it's a base64 string. If the decode fails, then I assume it's raw data.

    Note the validate=True keyword argument to b64decode. This is required in order for the assert to be generated by the decoder. Without it there will be no complaints about an illegal string.

    import base64, binascii
    
    try:
        image_data = base64.b64decode(my_image_string, validate=True)
    except binascii.Error:
        image_data = my_image_string
    

提交回复
热议问题