Check if a string is encoded in base64 using Python

前端 未结 10 2068
离开以前
离开以前 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:15

    def is_base64(s):
        s = ''.join([s.strip() for s in s.split("\n")])
        try:
            enc = base64.b64encode(base64.b64decode(s)).strip()
            return enc == s
        except TypeError:
            return False
    

    In my case, my input, s, had newlines which I had to strip before the comparison.

提交回复
热议问题