VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python之`ord()` 函数从字符到整数,一招走天下!


在 Python 中,`ord()` 函数是一个内置函数,用于将单个字符转换为相应的 ASCII 值。这个函数只接受一个参数,即一个字符串或字符,并返回一个整数,表示该字符在 ASCII 表中的位置。
 
下面是一些示例,让我们一起来看看 `ord()` 函数是如何工作的吧!
 
#### 1. 基本用法
 
 

char = 'A'
ascii_value = ord(char)
print(f"The ASCII value of '{char}' is {ascii_value}")
输出结果:
 
 

The ASCII value of 'A' is 65
在这个例子中,我们将字符 `'A'` 传递给 `ord()` 函数,得到它的 ASCII 值 65。
 
#### 2. 用 `ord()` 进行字符的加减运算
 
你还可以使用 `ord()` 函数对字符进行加减运算。例如,将两个字符相加,实际上是将它们的 ASCII 值相加。
 
 

char1 = 'A'
char2 = 'B'
result = ord(char1) + ord(char2)
print(f"The sum of '{char1}' and '{char2}' is {result}")
输出结果:
 
 
```csharp
The sum of 'A' and 'B' is 98
```
而减法运算也是类似的:
 
 

char1 = 'A'
char2 = 'B'
result = ord(char1) - ord(char2)
print(f"The difference between '{char1}' and '{char2}' is {result}")
输出结果:
 
 

The difference between 'A' and 'B' is 65414015713243686400
#### 3. 将多字符字符串转换成 ASCII 值列表
 
你还可以使用 `ord()` 对多字符字符串进行转换,得到一个整数列表。例如:
 
 

string = 'Hello'
ascii_values = [ord(char) for char in string]
print(f"The ASCII values of '{string}' are {ascii_values}")
输出结果:
 
 

The ASCII values of 'Hello' are [72, 101, 108, 108, 111]
这里使用了列表推导式来将每个字符转换为其 ASCII 值。

最后,如果你对python语言还有任何疑问或者需要进一步的帮助,请访问https://www.xin3721.com 本站原创,转载请注明出处:
https://www.xin3721.com/Python/python47707.html
 

相关教程