Python character and character value (ASCII or Unicode code value) conversion method

Source: Internet
Author: User
Purpose

Converts a character to the appropriate ASCII or Unicode code, or vice versa.

Method

For ASCII codes (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 that corresponds to the ASCII value, and one that accepts any type of return string format

The code is as follows:


>>> chr (97)
A
>>> STR (97)
' 97 '

Use map and the above functions to get a list of 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 ']

  • 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.