我想检查一个字符串是否是ASCII格式的。
我知道ord(),但是当我尝试ord('é')时,我有TypeError: ord()期望一个字符,但发现长度为2的字符串。我知道这是由我构建Python的方式引起的(如ord()的文档所解释的那样)。
还有别的办法吗?
我想检查一个字符串是否是ASCII格式的。
我知道ord(),但是当我尝试ord('é')时,我有TypeError: ord()期望一个字符,但发现长度为2的字符串。我知道这是由我构建Python的方式引起的(如ord()的文档所解释的那样)。
还有别的办法吗?
当前回答
要从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)
其他回答
def is_ascii(s):
return all(ord(c) < 128 for c in s)
就像@RogerDahl的回答一样,但是通过否定字符类和使用搜索而不是find_all或match来短路更有效。
>>> import re
>>> re.search('[^\x00-\x7F]', 'Did you catch that \x00?') is not None
False
>>> re.search('[^\x00-\x7F]', 'Did you catch that \xFF?') is not None
True
我想正则表达式对此进行了很好的优化。
在Python 3中,我们可以将字符串编码为UTF-8,然后检查长度是否保持不变。如果是,那么原始字符串是ASCII。
def isascii(s):
"""Check if the characters in string s are in ASCII, U+0-U+7F."""
return len(s) == len(s.encode())
要检查,通过测试字符串:
>>> isascii("♥O◘♦♥O◘♦")
False
>>> isascii("Python")
True
这样做怎么样?
import string
def isAscii(s):
for c in s:
if c not in string.ascii_letters:
return False
return True
Python 3.7新增功能(bpo32677)
不再对字符串进行烦人/低效的ascii检查,新的内置str/bytes/bytearray方法- .isascii()将检查字符串是否为ascii。
print("is this ascii?".isascii())
# True