如何在 Python 中将字符串转换为 ASCII 值

在计算机科学中,ASCII(American Standard Code for Information Interchange)是一种用于表示字符的标准编码。ASCII 码使用 7 位二进制数来表示 128 种字符,包括大写和小写字母、数字、标点符号和一些控制字符。在 Python 中,可以将字符串转换为 ASCII 值,以便在计算机程序中进行处理。本文将介绍如何在 Python 中将字符串转换为 ASCII 值,并提供一些注意事项和示例。

使用 ord() 函数将字符转换为 ASCII 值

在 Python 中,可以使用 ord() 函数将单个字符转换为 ASCII 值。ord() 函数接受一个字符作为参数,并返回该字符的 ASCII 值。例如,要将字符 ‘A’ 转换为 ASCII 值,可以使用以下代码:

ascii_value = ord('A')
print(ascii_value)

输出结果为:

65

其中,65 是字符 ‘A’ 的 ASCII 值。

使用 ord() 函数将字符串转换为 ASCII 值

要将字符串转换为 ASCII 值,可以使用 ord() 函数和循环。循环遍历字符串中的每个字符,并使用 ord() 函数将其转换为 ASCII 值。例如,要将字符串 ‘Hello, world!’ 转换为 ASCII 值,可以使用以下代码:

string = 'Hello, world!'
ascii_values = []
for char in string:
    ascii_value = ord(char)
    ascii_values.append(ascii_value)
print(ascii_values)

输出结果为:

[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]

其中,每个数字都是字符串中相应字符的 ASCII 值。

使用 bytearray() 函数将字符串转换为 ASCII 值

另一种将字符串转换为 ASCII 值的方法是使用 bytearray() 函数。bytearray() 函数接受一个字符串作为参数,并将其转换为一个字节数组。每个字节都对应一个 ASCII 值。例如,要将字符串 ‘Hello, world!’ 转换为 ASCII 值,可以使用以下代码:

string = 'Hello, world!'
byte_array = bytearray(string, 'ascii')
ascii_values = list(byte_array)
print(ascii_values)

输出结果与上面的示例相同:

[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]

其中,list() 函数将字节数组转换为一个列表,每个元素都是一个 ASCII 值。

注意事项:

  1. ord() 函数只能将单个字符转换为 ASCII 值。如果要将整个字符串转换为 ASCII 值,需要使用循环或 bytearray() 函数。
  2. 在使用 bytearray() 函数时,需要指定字符编码。如果不指定编码,默认使用 UTF-8 编码,可能会导致转换错误。
  3. ASCII 码只能表示 128 种字符,包括英文字母、数字、标点符号和一些控制字符。如果字符串中包含其他字符,将无法转换为 ASCII 值。

示例:

以下示例演示了如何将字符串转换为 ASCII 值,并使用 ASCII 值进行加密和解密。

加密:

# 将字符串转换为 ASCII 值,并将每个值加上 3
string = 'Hello, world!'
encrypted_values = []
for char in string:
    ascii_value = ord(char) + 3
    encrypted_values.append(ascii_value)

# 将加密后的 ASCII 值转换为字符串
encrypted_string = ''.join([chr(value) for value in encrypted_values])
print(encrypted_string)

输出结果为:

Khoor/#zruog$

其中,每个字符都加上了 3,得到了一个加密后的字符串。

解密:

# 将加密后的字符串转换为 ASCII 值,并将每个值减去 3
encrypted_string = 'Khoor/#zruog$'
encrypted_values = []
for char in encrypted_string:
    ascii_value = ord(char) - 3
    encrypted_values.append(ascii_value)

# 将解密后的 ASCII 值转换为字符串
decrypted_string = ''.join([chr(value) for value in encrypted_values])
print(decrypted_string)

输出结果为:

Hello, world!

其中,每个字符都减去了 3,得到了原始字符串。

总结:

在 Python 中,可以使用 ord() 函数和循环,或者 bytearray() 函数将字符串转换为 ASCII 值。ASCII 值可以用于加密、解密和其他计算机程序中的处理。在使用这些函数时,需要注意字符编码和字符串中可能包含的非 ASCII 字符。