我想检查一个字符串是否是ASCII格式。我知道ord(),但是当我尝试时ord('é'),我有TypeError: ord() expected a character, but string of length 2 found。我知道它是由我构建Python的方式引起的(如ord()文档中所述)。还有其他方法可以检查吗?
3 回答

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
我想你不是在问正确的问题 -
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"

元芳怎么了
TA贡献1798条经验 获得超7个赞
Python 3方式:
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
添加回答
举报
0/150
提交
取消