Skip to content
Advertisement

How can we print a list of ASCII characters to the console, except forthose characters which have an escape sequence?

For any ascii characters ch, I would like to print ch unless repr(ch) begins with a back-slash character.

I want to print a list of all of the “nice” ascii characters.

Failed Attempt

import re


characters = [chr(num) for num in range(256)]
# `characters` : a list such that every element
#                of the list is an ASCII character

escaped_chars = [repr(ch)[1:-1] for ch in characters]
# `escaped_chars`: a list of all ASCII character unless
#               the character is special
#               new line is stored as "n"
#               carriage return is stored as "r"

printables = "".join(filter(lambda s: s[0] != "\", escaped_chars))

print("n".join(re.findall('.{1,20}', "".join(printables))))

The console print-out is:

 !"#$%&'()*+,-./0123
456789:;<=>?@ABCDEFG
HIJKLMNOPQRSTUVWXYZ[
]^_`abcdefghijklmnop
qrstuvwxyz{|}~¡¢£¤¥¦
§¨©ª«¬®¯°±²³´µ¶·¸¹º»
¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ
ÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâã
äåæçèéêëìíîïðñòóôõö÷
øùúûüýþÿ

I seem to have printed a lot of weird unicode characters, such as ç and õ

Advertisement

Answer

import re

characters = [chr(num) for num in range(127)]
# `characters` : a list such that every element
#                of the list is an ASCII character

escaped_chars = [repr(ch)[1:-1] for ch in characters]
# `escaped_chars`: a list of all ASCII character unless
#               the character is special
#               new line is stored as "n"
#               carriage return is stored as "r"

printables = "".join(filter(lambda s: s[0] != "\", escaped_chars))

print("n".join(re.findall('.{1,20}', "".join(printables))))

As sj95126 wrote:

values above 127 aren’t ASCII characters

Here’s right code

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement