1

我正在尝试编写一个简短的脚本(用于教程)来显示前 128 个 ASCII 字符中的哪些是可打印的、可识别的字符。

以下使用 `is in string.printable' 的脚本部分有效,但仍会触发换行等内容。

是否可以再添加一两行来捕获这些控制字符并将其替换为空格,以便表格看起来不错并显示可打印的字符?

为菜鸟可读性而写成:

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)

闲置的:

在此处输入图像描述

复制/粘贴到 SE 中,包括四个空格:

   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
         )9IYiy

 *:JZjz
 +;K[k{
 ,<L\l|

-=M]m} .>N^n~ /?O_o

4

2 回答 2

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)检查字符的 可能更有效, c.

于 2017-11-17T00:35:38.287 回答
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
于 2017-11-17T01:30:56.830 回答