Comparison between chr, unichr, ord character functions in Python

高洛峰
Release: 2017-03-02 11:26:09
Original
2166 people have browsed it

chr, unichr, and ord can all be used for character type conversion in Python. Here we will briefly talk about the comparison between chr, unichr, and ord character functions in Python. Friends who need it can refer to it

  • ord is the abbreviation of unicode ordinal, that is, the number

  • chr is the abbreviation of character, that is, the character

  • ord and chr are converted correspondingly to each other.

  • But since chr is limited to ascii, the length is only 256, so there is one more unichr.

>>c = u'康'

>>c
u'\u5eb7'
>>ord(c)
24747
>>chr(24247)
ValueError: chr() arg not in range(256)
>>unichr(24247)
u'\u5eb7'
Copy after login

The chr() function takes an integer in the range (256) (that is, 0 to 255) as a parameter and returns a corresponding character. unichr() is the same, except that it returns Unicode characters. The parameter range of unichr(), which was added from Python 2.0, depends on how your Python was compiled. If it is Unicode configured as USC2, then its allowed range is range (65536) or 0x0000-0xFFFF; if it is configured as UCS4, then this value should be range (1114112) or 0x000000-0x110000. If the provided parameters are not within the allowed range, a ValueError exception will be reported.
The ord() function is the paired function of the chr() function (for 8-bit ASCII strings) or the unichr() function (for Unicode objects). It takes one character (a string of length 1) as a parameter, Returns the corresponding ASCII value, or Unicode value. If the given Unicode character exceeds your Python definition range, a TypeError exception will be raised.

>>> chr(65)
'A'
>>> ord('a')
97
>>> unichr(12345)
u'\u3039'
>>> chr(12345)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?  
   chr(12345)
ValueError: chr() arg not in range(256)
>>> ord(u&#39;\ufffff&#39;)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
   ord(u&#39;\ufffff&#39;)
TypeError: ord() expected a character, but string of length 2 found
>>> ord(u&#39;\u2345&#39;)
9029
Copy after login


Please pay attention to more related articles about the comparison between chr, unichr, ord character functions in Python PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!