我想检查一个字符串是否为ASCII格式。
我知道 ord() ,但是当我尝试 ord('é') 时,我使用的是 TypeError: ord() expected a character, but string of length 2 found 。我知道这是由我构建Python的方式引起的(正如 ord() 's documentation 中解释的那样)。
ord()
ord('é')
TypeError: ord() expected a character, but string of length 2 found
有没有其他检查的方法?
发布于 2008-10-13 00:30:43
def is_ascii(s): return all(ord(c) < 128 for c in s)
发布于 2008-10-13 00:30:32
我觉得你问的问题不对--
python中的字符串没有对应于'ascii‘、utf-8或任何其他编码的属性。字符串的来源(无论是从文件中读取,还是从键盘输入,等等)可能已经在ascii中编码了unicode字符串以生成您的字符串,但这是您需要找到答案的地方。
也许你可以问的问题是:“这个字符串是用ascii编码unicode字符串的结果吗?”--你可以通过尝试回答这个问题:
try: mystring.decode('ascii') except UnicodeDecodeError: print "it was not a ascii-encoded unicode string" else: