Pipanic
Pipanic

Reputation: 13

Display an ASCII Table in Python

I want to display an ASCII table of the characters from 32 to 127 (decimal), but instead of the decimal numbers I want it to display the hexadecimal ones with the according characters next to them so it can look like this:

20     21 !   22 "   23 #   24 $   25 %   26 &   27 '   28 (   29 )   2a *   2b +   2c ,   2d -   2e .   2f /   
30 0   31 1   32 2   33 3   34 4   35 5   36 6   37 7   38 8   39 9   3a :   3b ;   3c <   3d =   3e >   3f ?   
40 @   41 A   42 B   43 C   44 D   45 E   46 F   47 G   48 H   49 I   4a J   4b K   4c L   4d M   4e N   4f O   
50 P   51 Q   52 R   53 S   54 T   55 U   56 V   57 W   58 X   59 Y   5a Z   5b [   5c \   5d ]   5e ^   5f _   
60 `   61 a   62 b   63 c   64 d   65 e   66 f   67 g   68 h   69 i   6a j   6b k   6c l   6d m   6e n   6f o   
70 p   71 q   72 r   73 s   74 t   75 u   76 v   77 w   78 x   79 y   7a z   7b {   7c |   7d }   7e ~   

I need to use a 'for-loop' for this and have 16 characters per row as shown above.

So far I have this as a code, but it prints out the decimal numbers and I don't know how to make it print out the hexadecimal ones, also I don't know how to make the characters stay next to the hexadecimal ones and not above them:

for i in range(32, 127, 16):

   for characters in range(i, i+16):
      print('%5s'%chr(characters), end="")
   print()

   for decimal in range(i, i+16):
      print('%5s'%decimal, end="")
   print()

Upvotes: 0

Views: 1379

Answers (4)

Ahmed Tounsi
Ahmed Tounsi

Reputation: 1550

I suggest using the f-string syntax.

for i in range(32, 127, 16):
    for characters in range(i, i+16):
        print(f"{characters:2x} {chr(characters):<4}", end="")
    print()

Upvotes: 1

steviestickman
steviestickman

Reputation: 1251

You can also use the new style formatting

>>> '{:x} {:<4}'.format(65, chr(65))
'41 A    '

If you uncouple generating the strings from printing you get a little more readable code.

from itertools import islice
# cell generator
cells = (f"{i:x} {chr(i):<4}" for i in range(32, 127))

# cell printer
for _ in range(32, 127, 16):
    # for every row print the next 16 cells
    print(*islice(cells, 0, 16))

Upvotes: 1

arsha_ex
arsha_ex

Reputation: 128

Use %x:

for i in range(32, 127, 16):

   for characters in range(i, i+16):
      print('%2x %-4s'%(characters, chr(characters)) , end="")
   print()

Upvotes: 1

naszy
naszy

Reputation: 511

You can change the format specification; change the s to x (or X if you want uppercase letters in the hexadecimal numbers).

That is

print('%5x' % decimal, end="")

Upvotes: 2

Related Questions