如何检查Python中的字符串是否是ASCII格式的?

2024-05-01 21:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查字符串是否是ASCII格式的。

我知道ord(),但是当我尝试ord('é')时,我有TypeError: ord() expected a character, but string of length 2 found。我知道这是由我构建Python的方式造成的(如^{}'s documentation中所述)。

还有别的方法检查吗?


Tags: of方法字符串stringdocumentation格式方式ascii
3条回答
def is_ascii(s):
    return all(ord(c) < 128 for c in s)

Python3路:

isascii = lambda s: len(s) == len(s.encode())

要检查,请传递测试字符串:

str1 = "♥O◘♦♥O◘♦"
str2 = "Python"

print(isascii(str1)) -> will return False
print(isascii(str2)) -> will return True

我认为你问的问题不对——

python中的字符串没有对应于ascii、utf-8或任何其他编码的属性。字符串的来源(无论您是从文件中读取的,还是从键盘输入的,等等)可能已经用ascii编码了unicode字符串来生成字符串,但这就是您需要寻找答案的地方。

也许您可以问的问题是:“这个字符串是用ascii编码unicode字符串的结果吗?”--这个你可以回答 通过尝试:

try:
    mystring.decode('ascii')
except UnicodeDecodeError:
    print "it was not a ascii-encoded unicode string"
else:
    print "It may have been an ascii-encoded unicode string"

相关问题 更多 >