检查字符串是否只包含ASCII字符?

Jav*_*aSa 10 python python-2.7

如何在Python中检查字符串是否只包含ASCII字符?像Ruby这样的东西ascii_only?

我希望能够判断从文件读取的字符串特定数据是否在ascii中

war*_*iuc 22

在Python 3.7中添加了做你想要的方法:

str,bytesbytearray获得对新isascii()方法的支持,该方法可用于测试字符串或字节是否仅包含ASCII字符.


除此以外:

>>> all(ord(char) < 128 for char in 'string')
>>> True

>>> all(ord(char) < 128 for char in '??????')
>>> False
Run Code Online (Sandbox Code Playgroud)

另一个版本:

>>> def is_ascii(text):
    if isinstance(text, unicode):
        try:
            text.encode('ascii')
        except UnicodeEncodeError:
            return False
    else:
        try:
            text.decode('ascii')
        except UnicodeDecodeError:
            return False
    return True
...

>>> is_ascii('text')
>>> True

>>> is_ascii(u'text')
>>> True

>>> is_ascii(u'text-??????')
>>> False

>>> is_ascii('text-??????')
>>> False

>>> is_ascii(u'text-??????'.encode('utf-8'))
>>> False
Run Code Online (Sandbox Code Playgroud)

  • @Carpetsmoker &gt;我认为这总是会创建一个完整的列表?&lt; 不,不会。all 中的表达式是一个生成器,它一个接一个地输入字符。 (2认同)

rot*_*ten 6

如果你有 unicode 字符串,你可以使用“encode”函数,然后捕获异常:

try:
    mynewstring = mystring.encode('ascii')
except UnicodeEncodeError:
    print("there are non-ascii characters in there")
Run Code Online (Sandbox Code Playgroud)

如果有字节,可以导入 chardet 模块并检查编码:

import chardet

# Get the encoding
enc = chardet.detect(mystring)['encoding']
Run Code Online (Sandbox Code Playgroud)


Qui*_*inn 5

您还可以选择使用正则表达式来仅检查ascii字符。[\x00-\x7F]可以匹配一个ascii字符:

>>> OnlyAscii = lambda s: re.match('^[\x00-\x7F]+$', s) != None
>>> OnlyAscii('string')
True
>>> OnlyAscii('Tannh‰user')
False
Run Code Online (Sandbox Code Playgroud)