Python string.isascii() 函数用法

2023-09-17 22:21:19

如果字符串为空或字符串中的所有字符均为 ASCII,则 isascii() 方法返回 True。

ASCII 代表 美国信息交换标准代码。它是一种字符尾编码标准,使用 0 到 127 之间的数字来表示英文字符。例如,字符 A 的 ASCII 代码为 65,Z 的 ASCII 代码为 90。同样,ASCII 代码 97 表示 a,122 表示 z。ASCII 代码还用于表示制表符、表单馈送、回车符以及一些符号等字符。 ASCII 字符的代码点范围为 U+0000-U+007F。

语法:(Syntax:)

str.isascii()

参数:

没有。

返回值:

如果字符串为 ASCII,则返回 True,否则返回 False。

下面的示例演示 isascii() 方法。

mystr = 'ABC'
print(mystr.isascii())
mystr = '012345'
print(mystr.isascii())
mystr = 'ABC'
print(mystr.isascii())

输出:

True
True
True

空字符串、换行符符号和数字也是 ASCII 字符。

\t
mystr = '#'
print(mystr.isascii())
mystr = '$'
print(mystr.isascii())
mystr = ''
print(mystr.isascii())
mystr = '\n'
print(mystr.isascii())

输出:

True
True
True
True

isascii() 方法还检查 ASCII 的 Unicode 字符,如下所示。

mystr = '/u0000' # Unicode of Null
print(mystr.isascii())
mystr = '/u0041' # Unicode of A
print(mystr.isascii())
mystr = '/u0061'  # Unicode of a
print(mystr.isascii())
mystr = '/u007f' # Unicode of DEL
print(mystr.isascii())

输出:

True
True
True
True

isascii() 方法为任何非 ASCII 字符返回 False。

\t
mystr = '/u00e2' # Unicode of â
print(mystr.isascii())
mystr = '/u00f8' # Unicode of ø
print(mystr.isascii())
mystr = 'õ'  
print(mystr.isascii())
mystr = 'Å' 
print(mystr.isascii())
mystr = 'ß'   # German letter
print(mystr.isascii())

输出:

False
False
False
False
False

本文内容总结: