Why does the following code not output the corresponding letters correctly?

104 views Asked by At

Why does the following code not output the corresponding letters correctly?

It outputs number to letter is['\x03', '\x03']

final_numbers = [3, 3]
final_letters = []

for i in range(len(final_numbers)):
    print(i)
    number_to_letter=chr(final_numbers[i])
    final_letters.append(number_to_letter)

print ("number to letter is" + str(final_letters))
1

There are 1 answers

2
ppwater On BEST ANSWER

chr(3) returns the character whose ASCII code is 3 (which is '\x03').
To convert number to string (int-str) You have to do str() not chr()

So do like this:

final_numbers = [3, 3]
final_letters = []

for i in range(len(final_numbers)):
    print(i)
    number_to_letter=str(final_numbers[i])
    final_letters.append(number_to_letter)

print ("number to letter is" + str(final_letters))

Or this if you want to do chr() (try to guess what the results are)

final_numbers = [115, 116, 97, 99, 107, 32, 111, 118, 101, 114, 102, 108, 111, 119]
final_letters = []

for i in range(len(final_numbers)):
    print(i)
    number_to_letter=chr(final_numbers[i])
    final_letters.append(number_to_letter)

print ("number to letter is" + str(final_letters))