Python chr (), unichr (), and ord ()

Source: Internet
Author: User

Chr (), unichr (), and ord ()

The chr () function uses a range (0 to 256 ~ 255) an integer is used as a parameter and a corresponding character is returned. Unichr () is the same as it, but only returns Unicode characters. The parameter range of unichr () added from Python 2.0 depends on how your Python is compiled. If Unicode is configured as USC2, the allowed range is range (65536) or 0x0000-0xFFFF. If it is configured as UCS4, the value should be range (1114112) or 0x000000-0x110000. If the provided parameter is not within the permitted range, a ValueError exception is reported.

The ord () function is a paired function of the chr () function (for an 8-bit ASCII string) or unichr () function (for a Unicode object, it takes a single character (a string with a length of 1) as a parameter and returns the corresponding ASCII value or Unicode value. If the Unicode character is out of your Python defined range, A TypeError exception is thrown.

>>> Chr (50)

'2'

>>> Ord ('F ')

102

>>> Unichr (20013)

U' \ u4e2d'

>>> Print unichr (20013)

Medium

>>> Chr (1, 20013)

Traceback (most recent call last ):

File "<stdin>", line 1, in?

Chr (1, 20013)

ValueError: chr () arg not in range (256)

>>> Ord (U' \ u4e2d ')

Traceback (most recent call last ):

File "<stdin>", line 1, in?

Ord (U' \ u4e2d ')

TypeError: ord () expected a character, but string of length 2 found

>>> Ord (U' \ u2345 ')

9029

When all encoding formats fail, you can use unichr (ord (single character). encode ('utf-8') for encoding. The output must be UTF-8.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.