Python 字符的ASCII码值
ASCII即American Standard Code for Information Interchange(美国信息交换标准代码),是一个用于显示文本的标准字符集。每个字符都被分配一个唯一的ASCII码值,范围从0到127,总共128个字符。
ord()函数
Python中的ord()
函数可以用来获取字符的ASCII码值。该函数接受一个字符串(只包含一个字符)作为参数,并返回对应字符的ASCII码值。下面我们来看一个简单的示例:
char = 'A'
ascii_value = ord(char)
print(ascii_value)
运行上面的代码,你会得到输出65
。这是因为大写字母’A’的ASCII码值为65。
示例代码
下面是一个完整的示例代码,展示了如何使用ord()
函数打印字符串中每个字符的ASCII码值:
string = 'Hello, World!'
for char in string:
ascii_value = ord(char)
print(f'The ASCII value of {char} is {ascii_value}.')
运行上述代码,你将会看到如下输出:
The ASCII value of H is 72.
The ASCII value of e is 101.
The ASCII value of l is 108.
The ASCII value of l is 108.
The ASCII value of o is 111.
The ASCII value of , is 44.
The ASCII value of is 32.
The ASCII value of W is 87.
The ASCII value of o is 111.
The ASCII value of r is 114.
The ASCII value of l is 108.
The ASCII value of d is 100.
The ASCII value of ! is 33.
应用案例
1. 字符串加密
在密码学中,经常会用到将字符串转换为ASCII码值进行加密的技术。通过ord()
函数,我们可以很方便地将字符串转换为ASCII码值,然后再根据一定的算法进行加密。
def encrypt_string(string):
encrypted_string = ''
for char in string:
ascii_value = ord(char)
encrypted_ascii = ascii_value + 3 # 将ASCII码值加3
encrypted_char = chr(encrypted_ascii) # 将加密后的ASCII码值转换回字符
encrypted_string += encrypted_char
return encrypted_string
original_string = 'Hello, World!'
encrypted_string = encrypt_string(original_string)
print(f'The encrypted string is: {encrypted_string}')
运行上述代码,你将得到如下输出:
The encrypted string is: Khoor/#Zruog/
2. 字符串排序
有时候我们需要根据字符串中字符的ASCII码值对字符串进行排序。下面是一个简单的示例代码,演示了如何通过比较字符的ASCII码值来实现对字符串的排序:
def sort_string(string):
sorted_string = ''.join(sorted(string, key=lambda x: ord(x)))
return sorted_string
unsorted_string = 'Python'
sorted_string = sort_string(unsorted_string)
print(f'The sorted string is: {sorted_string}')
运行上面的代码,你会得到输出Phnoty
,即按照字母的ASCII码值顺序对字符串进行排序。
总结
通过ord()
函数,我们可以方便地获取字符的ASCII码值,从而实现诸如加密、排序等操作。掌握这一函数对于处理字符串时能提供便利,并且在需要对字符进行ASCII编码处理时能够灵活运用。