0

I tried to print the escape sequence characters or the ASCII representation of numbers in Python in a for loop.

Like:

for i in range(100, 150):
    b = "\%d" %i
    print(b)

I expected the output like,

A
B
C

Or something.

But I got like,

\100
\101

How to print ASCII representation of the numbers?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • Like others have said, you can do `chr(i)` to get the ASCII character represented by `i`, and that is the better way to do it. But you could also achieve it with percent-formatting, with `'%c' % i`. It's just good to know all your options. – nog642 Oct 19 '19 at 04:23

2 Answers2

2

There's a builtin function for python called ord and chr

ord is used to get the value of ASCII letter, for example:

print(ord('h'))

The output of the above is 104

ord only support a one length string

chr is inverse of ord

print(chr(104))

The output of the above is 'h'

chr only supports integer. float, string, and byte doesn't support

chr and ord are really important if you want to make a translation of a text file (encoded text file)

1

You can use the ord() function to print the ASCII value of a character.

print(ord('b'))

> 98

Likewise, you can use the chr() function to print the ASCII character represented by a number.

print(chr(98))

> b

Nick Reed
  • 4,989
  • 4
  • 17
  • 37