I like the approach that looks like this:
base64chars = list(chars('AZ', 'az', '09', '++', '//'))
It can certainly be implemented with great comfort, but it is quick and easy and easy to read.
Python 3
Generator Version:
def chars(*args): for a in args: for i in range(ord(a[0]), ord(a[1])+1): yield chr(i)
Or if you like the listings:
def chars(*args): return [chr(i) for a in args for i in range(ord(a[0]), ord(a[1])+1)]
The first gives:
print(chars('ĀĈ')) <generator object chars at 0x7efcb4e72308> print(list(chars('ĀĈ'))) ['Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ']
and the second gives:
print(chars('ĀĈ')) ['Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ']
This is really convenient:
base64chars = list(chars('AZ', 'az', '09', '++', '//')) for a in base64chars: print(repr(a),end='') print('') for a in base64chars: print(repr(a),end=' ')
exits
'A''B''C''D''E''F''G''H''I''J''K''L''M''N''O''P''Q''R''S''T''U''V''W''X''Y''Z''a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z''0''1''2''3''4''5''6''7''8''9''+''/' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' '+' '/'
Why list() ? Without base64chars can become a generator (depending on the implementation you choose) and, therefore, can only be used in the very first cycle.
Python 2
Similar ones can be archived with Python 2. But this is much more complicated if you want to also support Unicode. To encourage you to stop using Python 2 in favor of Python 3, I don't want to offer a Python 2 solution here;)
Try avoiding Python 2 today for new projects. Also, try porting your old projects to Python 3 first before expanding them - in the end, it will be worth the effort!
Proper Unicode handling in Python 2 is extremely complex, and it is almost impossible to add Unicode support for Python 2 projects if that support was not created from the very beginning.
Specifies how to back up this file in Python 2:
- Use
xrange instead of range - Create a second function (
unicodes ?) To handle Unicode:- Use
unichr instead of chr to return unicode instead of str - Never forget to feed
unicode strings as args to make ord and array index work correctly