我正在尝试编写一个简短的脚本(用于教程),以显示前128个ASCII字符中的哪一个是可打印的,可识别的字符。
使用`is in string.printable'的以下脚本部分有效,但仍然会触发换行等事情。
我可以添加一两行来捕获并用空格替换这些控制字符,以便表格看起来不错并显示可打印的字符吗?
写出了noob-readability的缩写:
import string
lines = []
for i in range(8):
line = []
for j in range(16):
k = i + j *16
thing = chr(k)
if thing not in string.printable:
thing = ' '
line.append(thing)
lines.append(line)
for line in lines:
print "".join(line)
IDLE:
复制/粘贴到SE中,包括四个空格:
0@P`p
!1AQaq
"2BRbr
#3CScs
$4DTdt
%5EUeu
&6FVfv
'7GWgw
(8HXhx
)9IYiy
*:JZjz
+;K[k{
,<L\l|
- = M]米} 。将N ^ N〜 /?O_o
答案 0 :(得分:1)
更新了代码,根据OP的评论替换不可打印的字符。
from string import printable, whitespace
replace_ch = ' ' # The character to replace non-printable characters with
whitespace_ch = ' ' # The character to replace whitespace characters with
# For console output
out_width = 8
out_height = 16
chars = [chr(i) for i in range(128)]
# Replace whitespace characters
chars = [whitespace_ch if c in whitespace else c for c in chars]
# Replace non-printable characters
chars = [c if c in printable else replace_ch for c in chars]
# Form lines for printing
lines = [[chars[i + j * out_height] for j in range(out_width)] for i in range(out_height)]
for line in lines:
print(''.join(line))
输出:
0@P`p
!1AQaq
"2BRbr
#3CScs
$4DTdt
%5EUeu
&6FVfv
'7GWgw
(8HXhx
)9IYiy
*:JZjz
+;K[k{
,<L\l|
-=M]m}
.>N^n~
/?O_o
另一种方法是简单地避免ASCII的前32个字符,因为它们被定义为控制字符。检查字符ord(c)
的{{1}}可能更有效。
答案 1 :(得分:1)
import string
columns = []
height = 10
whitespace_map = {
'\t': 'TAB',
'\n': 'LF',
'\r': 'CR',
'\x0b': 'VT',
'\x0c': 'FF',
}
i = 0
j = height
while i < len(string.printable):
column = string.printable[i:j]
columns.append(column)
i += height
j += height
k = 0
while k < height:
for column in columns:
if k > len(column):
break
c = column[k]
if c in string.whitespace and c != ' ':
c = whitespace_map[c]
# Alternative: c = ' '
print('{: <5}'.format(c), end='')
print()
k += 1
打印:
0 a k u E O Y ) = {
1 b l v F P Z * > |
2 c m w G Q ! + ? }
3 d n x H R " , @ ~
4 e o y I S # - [
5 f p z J T $ . \ TAB
6 g q A K U % / ] LF
7 h r B L V & : ^ CR
8 i s C M W ' ; _ VT
9 j t D N X ( < ` FF