Python ascii() 函数是一个内置函数,它返回指定对象的可读版本。在这里,对象可以是 Strings、Tuples、Lists 等。如果此函数遇到非 ASCII 字符,则会将其替换为转义字符,例如 \x、\u 和 \U。
当我们需要确保最终结果符合 ASCII 标准时,此功能非常有用,ASCII 标准是一种字符编码标准,代表美国信息交换标准。
语法
以下是 Python ascii() 函数的语法 -
ascii(object)
参数
Python ascii() 函数接受单个参数 -
- object − 它表示一个对象,例如列表、字符串或元组。
返回值
Python ascii() 函数返回一个 String,其中包含对象的可打印表示形式。
例子
让我们通过一些示例来了解 ascii() 函数是如何工作的 -
示例 1
以下示例演示如何使用 Python ascii() 函数。在这里,我们定义一个字符串并应用 ascii() 函数将其转换为带有 ASCII 字符的 String。结果将与原始字符串相同,因为它已经包含 ASCII 字符。
orgnl_str = "Learn Python Methods"
new_ascii_str = ascii(orgnl_str)
print("The new ascii representation of given string:", new_ascii_str)
当我们运行上述程序时,它会产生以下结果——
The new ascii representation of given string: 'Learn Python Methods'
示例 2
在下面的示例中,我们将定义一个包含一些非 ASCII 字符的字符串,并应用 ascii() 函数将其转换为包含ASCII字符的字符串。
orgnl_str = "Learn Pythön Methods"
new_ascii_str = ascii(orgnl_str)
print("The new ascii representation of given string:", new_ascii_str)
当我们运行上述程序时,它会产生以下结果——
The new ascii representation of given string: 'Learn Pyth\xf6n Methods'
示例 3
下面的代码显示了如何使用 ascii() 函数将包含非 ASCII 字符的列表转换为包含包含 ASCII 字符的列表。
orgnl_lst = [71, 87, "é", "→",5]
new_ascii_lst = ascii(orgnl_lst)
print("The new ascii representation of given list:", new_ascii_lst)
上述代码的输出如下 -
The new ascii representation of given list: [71, 87, '\xe9', '\u2192', 5]
示例 4
在下面的代码中,将创建一个名为 'orgnl_set' 的 set。然后使用 ascii() 函数替换集合中存在的所有元素。在这里,我们检索带有 ASCII 字符的集合。
orgnl_set = {"©", "¥", "é", "→"}
new_ascii_set = ascii(orgnl_set)
print("The new ascii representation of given set:", new_ascii_set)
以下是上述代码的输出 -
The new ascii representation of given set: {'\xa5', '\xa9', '\xe9', '\u2192'}