Home > Backend Development > Python Tutorial > Introduction to Python functions: introduction and examples of ord function

Introduction to Python functions: introduction and examples of ord function

王林
Release: 2023-11-04 10:17:04
Original
10329 people have browsed it

Introduction to Python functions: introduction and examples of ord function

Introduction to Python functions: Introduction and examples of ord function

In Python programming, the ord() function is a very useful function, which is used to return a given The Unicode value of the character, that is, the position of the character in the Unicode table. This article will introduce the usage, syntax and some examples of the ord() function.

1. The syntax of the ord() function

The syntax of the ord() function is very simple, with only one parameter: an ASCII character.

ord(c)

Parameter description:

c -- Character, it can also be a hexadecimal number.

Return value:

The return value is an integer, indicating the position of the character in Unicode. For example, ord("a") returns 97, ord("€") returns 8364, ord("中") returns 20013.

2. Examples of ord() function

The following are some example codes of the ord() function:

  1. Example 1: Return the Unicode value corresponding to the character
print(ord('a'))  # 97
print(ord('€'))  # 8364
print(ord('中'))  # 20013
Copy after login
  1. Example 2: Use a for loop to traverse the characters in the string and return their Unicode values ​​
str = "hello, world!"
for i in str:
    print(f"字符{i}的Unicode值为", ord(i))
Copy after login

The running results are as follows:

字符h的Unicode值为 104
字符e的Unicode值为 101
字符l的Unicode值为 108
字符l的Unicode值为 108
字符o的Unicode值为 111
字符,的Unicode值为 44
字符  的Unicode值为 32
字符w的Unicode值为 119
字符o的Unicode值为 111
字符r的Unicode值为 114
字符l的Unicode值为 108
字符d的Unicode值为 100
字符!的Unicode值为 33
Copy after login
  1. Example 3: Convert Unicode values ​​to corresponding characters
print(chr(97))  # a
print(chr(8364))  # €
print(chr(20013))  # 中
Copy after login

The above is the introduction and sample code of the ord() function. The ord() function is a very simple but practical function that is often used when processing strings. I hope this article can help everyone use the ord() function in Python programming.

The above is the detailed content of Introduction to Python functions: introduction and examples of ord function. For more information, please follow other related articles on the PHP Chinese website!

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