Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: extended ASCII codes

Hi I want to know how I can append and then print extended ASCII codes in python. I have the following.

code = chr(247)

li = []
li.append(code)
print li

The result python print out is ['\xf7'] when it should be a division symbol. If I simple print code directly "print code" then I get the division symbol but not if I append it to a list. What am I doing wrong?

Thanks.

like image 702
user1831677 Avatar asked Jan 21 '14 09:01

user1831677


People also ask

Does Python support extended ASCII?

There is no such thing as "extended ASCII", there are many different encodings in which 247 can mean different things. You need to decode the string with the right encoding.

What are extended ASCII codes?

Extended ASCII means an eight-bit character encoding that includes (most of) the seven-bit ASCII characters, plus additional characters.

How do I get extended ASCII characters?

On a standard 101 keyboard, special extended ASCII characters such as é or ß can be typed by holding the ALT key and typing the corresponding 4 digit ASCII code. For example é is typed by holding the ALT key and typing 0233 on the keypad.

Is there ASCII code in Python?

To get ascii value of char python, the ord () method is used. It is in-built in the library of character methods provided by Python. ASCII or American Standard Code for Information Interchange is the numeric value that is given to different characters and symbols.


2 Answers

You probably want the charmap encoding, which lets you turn unicode into bytes without 'magic' conversions.

s='\xf7'
b=s.encode('charmap')
with open('/dev/stdout','wb') as f:
    f.write(b)
    f.flush()

Will print ÷ on my system.

Note that 'extended ASCII' refers to any of a number of proprietary extensions to ASCII, none of which were ever officially adopted and all of which are incompatible with each other. As a result, the symbol output by that code will vary based on the controlling terminal's choice of how to interpret it.

like image 72
Perkins Avatar answered Oct 04 '22 04:10

Perkins


When you print a list, it outputs the default representation of all its elements - ie by calling repr() on each of them. The repr() of a string is its escaped code, by design. If you want to output all the elements of the list properly you should convert it to a string, eg via ', '.join(li).

Note that as those in the comments have stated, there isn't really any such thing as "extended ASCII", there are just various different encodings.

like image 39
Daniel Roseman Avatar answered Oct 04 '22 02:10

Daniel Roseman