Alex Rivera | Logout

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

Asked 2011-05-05T00:42:45.807
144

I'm looking for something like the following:

import ascii

print(ascii.charlist())

Which would return something like ["A", "B", "C", "D" ... ].

Edit
Report

3 Answers

39

Here it is:

[chr(i) for i in range(128)]
answered 2011-05-05T00:47:05.487
21

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
answered 2011-05-05T00:50:53.710
7

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
{
|
}
~
answered 2011-05-05T00:48:26.703

Your Answer