Is there a good way to check if a string is encoded in base64
using Python?
相关问题
- Views base64 encoded blob in HTML with PHP
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
I was looking for a solution to the same problem, then a very simple one just struck me in the head. All you need to do is decode, then re-encode. If the re-encoded string is equal to the encoded string, then it is base64 encoded.
Here is the code:
That's it!
Edit: Here's a version of the function that works with both the string and bytes objects in Python 3:
Using Python RegEx
This isn't possible. The best you could do would be to verify that a string might be valid Base 64, although many strings consisting of only ASCII text can be decoded as if they were Base 64.
@geoffspear is correct in that this is not 100% possible but you can get pretty close by checking the string header to see if it matches that of a base64 encoded string (re: How to check whether a string is base64 encoded or not).
Also not that in my case I wanted to return false if the string is empty to avoid decoding as there's no use in decoding nothing.
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 tob64decode
. 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.