我想检查一个字符串是否是ASCII格式的。
我知道ord(),但是当我尝试ord('é')时,我有TypeError: ord()期望一个字符,但发现长度为2的字符串。我知道这是由我构建Python的方式引起的(如ord()的文档所解释的那样)。
还有别的办法吗?
我想检查一个字符串是否是ASCII格式的。
我知道ord(),但是当我尝试ord('é')时,我有TypeError: ord()期望一个字符,但发现长度为2的字符串。我知道这是由我构建Python的方式引起的(如ord()的文档所解释的那样)。
还有别的办法吗?
当前回答
import re
def is_ascii(s):
return bool(re.match(r'[\x00-\x7F]+$', s))
要包含一个空字符串作为ASCII,将+改为*。
其他回答
def is_ascii(s):
return all(ord(c) < 128 for c in s)
我使用以下方法来确定字符串是ascii还是unicode:
>> print 'test string'.__class__.__name__
str
>>> print u'test string'.__class__.__name__
unicode
>>>
然后使用一个条件块来定义函数:
def is_ascii(input):
if input.__class__.__name__ == "str":
return True
return False
要从Python 2.6(以及Python 3.x)改进Alexander的解决方案,您可以使用helper模块curses。ASCII和使用curses.ascii.isascii()函数或其他各种:https://docs.python.org/2.6/library/curses.ascii.html
from curses import ascii
def isascii(s):
return all(ascii.isascii(c) for c in s)
为了防止代码崩溃,可能需要使用try-except来捕获TypeErrors
>>> ord("¶")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
例如
def is_ascii(s):
try:
return all(ord(c) < 128 for c in s)
except TypeError:
return False
这样做怎么样?
import string
def isAscii(s):
for c in s:
if c not in string.ascii_letters:
return False
return True