ascii()
方法将非可打印字符替换为其对应的 ASCII 值并返回。
示例
text = 'Pythön is interesting'
# replace ö with its ascii value
print(ascii(text)) # Output: 'Pyth\xf6n is interesting'
ascii() 语法
ascii()
的语法是:
ascii(object)
ascii() 参数
ascii()
方法接受一个参数:
ascii() 返回值
ascii()
方法返回:
object
中非可打印字符对应的可打印等效字符。
示例 1: Python ascii()
text1 = '√ represents square root'
# replace √ with ascii value
print(ascii(text1))
text2 = 'Thör is coming'
# replace ö with ascii value
print(ascii(text2))
输出
'\u221a represents square root' 'Th\xf6r is coming'
在上面的示例中,我们使用了 ascii() 方法将非可打印字符替换为其对应的 ASCII 值。
该方法将:
- text1 中的
√
替换为\u221a
- text2 中的
ö
替换为\xf6n
示例 2: 对列表使用 ascii()
list = ['Python', 'öñ', 5]
# ascii() with a list
print(ascii(list))
输出
['Python', 'Pyth\xf6\xf1', 5]
在上面的示例中,我们对一个列表使用了 ascii()
方法。该方法将非 ASCII 字符 ö
替换为 \xf6
,将 ñ
替换为 \xf1
。
示例 3: 对集合使用 ascii()
set = {'Π', 'Φ', 'η'}
// ascii() with a set
print(ascii(set))
输出
{'\u03b7', '\u03a0', '\u03a6'}
在上面的示例中,我们对一个集合使用了 ascii()
方法。
该方法将集合中的每个非可打印字符作为参数,并用其对应的 ASCII 值替换它们。
示例 4: 对元组使用 ascii()
tuple = ('ö', '√', '¶','Ð','ß' )
// ascii() with a tuple
print(ascii(tuple))
输出
('\xf6', '\u221a', '\xb6', '\xd0', '\xdf')
在这里,我们对一个元组使用了 ascii()
方法。该方法将元组中的每个非可打印字符更改为其可打印的 ASCII 值。
另请阅读