Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of all the ASCII characters using Python?

Tags:

python

ascii

People also ask

How many ASCII characters are there in Python?

Remember: ASCII defines 128 characters which map from 0 to 127. According to stackoverflow Unicode allows for 17 planes, each of 65,536 possible characters (or 'code points'). This gives a total of 1,114,112 possible characters.

How do you use ASCII characters in Python?

The ascii() method in Python returns a string containing a printable representation of an object for non-alphabets or invisible characters such as tab, carriage return, form feed, etc. It escapes the non-ASCII characters in the string using \x , \u or \U escapes.


The constants in the string module may be what you want.

All ASCII capital letters:

>>> import string
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

All printable ASCII characters:

>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

For every single character defined in the ASCII standard, use chr:

>>> ''.join(chr(i) for i in range(128))
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'

Here it is:

[chr(i) for i in range(128)]

ASCII defines 128 characters whose byte values range from 0 to 127 inclusive. So to get a string of all the ASCII characters, you could just do

''.join(chr(i) for i in range(128))

Only 100 of those are considered printable. The printable ASCII characters can be accessed via

import string
string.printable

Since ASCII printable characters are a pretty small list (bytes with values between 32 and 126 inclusive), it's easy enough to generate when you need:

>>> for c in (chr(i) for i in range(32, 127)):
...     print(c)
... 
 
!
"
#
$
%
... # a few lines removed :)
y
z
{
|
}
~

for i in range(0, 128):
    print(chr(i))

You can do this without a module:

characters = list(map(chr, range(97, 123)))

Type characters and it should print ["a","b","c", ... ,"x","y","z"]. For uppercase use:

characters = list(map(chr, range(65, 91)))

Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range() to add more characters to the list.
map() calls chr() every iteration of the range().