sdasdadas
sdasdadas

Reputation: 25116

Is there an easy way to represent the base64 alphabet in a Python list?

The alphabet (and its indices) can be found here:

http://www.garykessler.net/library/base64.html

Is there a shorter way than alphabet = ['A','B',...] of representing this alphabet?

Upvotes: 1

Views: 2109

Answers (3)

minopret
minopret

Reputation: 4806

Let's call this easy and short if your heart believes.

We can make base64 encoding provide its cipher alphabet.

#!python3
'Retrieve the cipher alphabet from the base64 module.'
import base64
def b64alphabet() -> str:
    '''
    >>> print(b64alphabet())
    ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
    '''
    loose = (range(i, i + 4) for i in range(0, 64, 4)) # ((0, 1, 2, 3), (4, ...), ..., (..., 63))
    tight = ((a << 2 | b >> 4, b << 4 | c >> 2, c << 6 | d) for a, b, c, d in loose)
    shave = bytes(value.to_bytes(2)[1] for group in tight for value in group)
    alpha = base64.b64encode(shave).decode('utf-8')
    return alpha
if __name__ == "__main__":
    import doctest
    doctest.testmod()

Upvotes: 0

Volatility
Volatility

Reputation: 32300

You can use the string module

import string
alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798794

Strings are sequences too.

'ABCD...'

Upvotes: 4

Related Questions