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

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


我知道ord(),但是当我尝试时ord('é'),我有TypeError: ord() expected a character, but string of length 2 found。我知道它是由我构建Python的方式引起的(如ord()文档中所述)。


还有其他方法可以检查吗?


狐的传说
浏览 2512回答 3
3回答

潇潇雨雨

def is_ascii(s):&nbsp; &nbsp; return all(ord(c) < 128 for c in s)

慕尼黑8549860

我想你不是在问正确的问题 -python中的字符串没有与'ascii',utf-8或任何其他编码对应的属性。你的字符串的来源(无论你是从文件中读取,从键盘输入等)都可能在ascii中编码了一个unicode字符串来生成你的字符串,但这就是你需要去寻找答案的地方。也许你可以问的问题是:“这个字符串是在ascii中编码unicode字符串的结果吗?” - 您可以通过尝试来回答:try:&nbsp; &nbsp; mystring.decode('ascii')except UnicodeDecodeError:&nbsp; &nbsp; print "it was not a ascii-encoded unicode string"else:&nbsp; &nbsp; print "It may have been an ascii-encoded unicode string"

元芳怎么了

Python 3方式:isascii = lambda s: len(s) == len(s.encode())要检查,请传递测试字符串:str1 = "♥O◘♦♥O◘♦"str2 = "Python"print(isascii(str1)) -> will return Falseprint(isascii(str2)) -> will return True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python