This article mainly introduces Python character and character value (ASCII or Unicode code value) conversion methods, that is, the string in the ASCII value or between Unicode values and conversion methods, the need for friends can refer to the
Objective
Converts a character to the appropriate ASCII or Unicode code, or to the opposite operation.
Method
For ASCII code (0~255 range)
The code is as follows:
>>> Print ord (' A ')
65
>>> Print Chr (65)
A
For Unicode characters, note that only Unicode characters of length 1 are received
The code is as follows:
>>> Print ord (U ' u54c8 ')
21704
>>> print UNICHR (21704)
Ha
>>> Print repr (UNICHR (21704))
U ' U54c8 '
Chr () differs from STR (), a value that receives only 0~255 returns the character corresponding to the ASCII value, one that accepts any type return string format
The code is as follows:
>>> chr (97)
A
>>> STR (97)
' 97 '
Use the map and the above functions to get a list containing character values or code values
The code is as follows:
>>> Print Map (ord, (U ' u54c8 ', U ' u54c9 '))
[21704, 21705]
>>> Print Map (Unichr,range (21704,21707))
[u ' U54c8 ', U ' u54c9 ', U ' u54ca ']