Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting newline character after every 76 characters in a base64 string

Tags:

python

base64

I am trying to convert bitmap images into a base64 string before inserting it into database as binary blobs. The base64 string needs to be encoded in such a way that their is a new line character after every 76 characters. What is the best pythonic way of doing this?

like image 589
nashr rafeeg Avatar asked May 20 '10 08:05

nashr rafeeg


2 Answers

For Python version 3:

import base64
base64.encodebytes(s)

https://docs.python.org/3/library/base64.html#base64.encodebytes

Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME).

Example:

>>> print(base64.encodebytes(b'a' * 100).decode())
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==

>>> 

For Python version 2:

import base64
base64.encodestring(s)

http://docs.python.org/library/base64.html

Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always including an extra trailing newline ('\n').

The docs for version 2 could certainly be written more clearly, but it does what you want.

Example:

>>> print base64.encodestring('a'*100)
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==

>>> 
like image 156
mpb Avatar answered Oct 13 '22 06:10

mpb


'\n'.join(s[pos:pos+76] for pos in xrange(0, len(s), 76))
like image 36
nosklo Avatar answered Oct 13 '22 06:10

nosklo