在 Python 中检查字符串是否为 ASCII 您所在的位置:网站首页 将字符串good的ascii码 在 Python 中检查字符串是否为 ASCII

在 Python 中检查字符串是否为 ASCII

#在 Python 中检查字符串是否为 ASCII| 来源: 网络整理| 查看: 265

使用 str.isascii() 方法检查字符串是否为 ASCII,例如 if my_str.isascii():。 如果字符串为空或字符串中的所有字符都是 ASCII,则 str.isascii() 方法返回 True,否则返回 False。

my_str = 'www.jiyik.com' if my_str.isascii(): # 👇️ this runs print('The string contains only ASCII characters') else: print('The string does NOT contain only ASCII characters') print('jiyik'.isascii()) # 👉️ True print('www jiyik'.isascii()) # 👉️ True print(''.isascii()) # 👉️ True print('ab фг'.isascii()) # 👉️ False

在 Python 中检查字符串是否为 ASCII

我们使用 str.isascii() 方法来检查字符串是否仅包含 ASCII 字符。

如果字符串为空或字符串中的所有字符都是 ASCII,str.isascii 方法返回 True,否则返回 False。

print(''.isascii()) # 👉️ True print('JIYIK'.isascii()) # 👉️ True print('WWW JIYIK'.isascii()) # 👉️ True print('WWW_JIYIK!.?'.isascii()) # 👉️ True print('ФФФ'.isascii()) # 👉️ False

ASCII 字符的代码点在 U+0000-U+007F 范围内。

如果我们认为空字符串不是 ASCII,请检查字符串的长度。

my_str = '' if my_str.isascii() and len(my_str) > 0: print('The string contains only ASCII characters') else: # 👇️ this runs print('The string does NOT contain only ASCII characters')

或者,我们可以使用 try/except 语句。

使用 try/except 检查字符串是否为 ASCII

要检查字符串是否为 ASCII:

使用 str.encode() 方法使用 ASCII 编码对字符串进行编码。在 except 块中捕获潜在的 UnicodeEncodeError 异常。如果 str.encode() 方法成功运行,则字符串为 ASCII。 def is_ascii(string): try: string.encode('ascii') except UnicodeEncodeError: return False else: return True print(is_ascii('jiyik')) # 👉️ True print(is_ascii('www jiyik')) # 👉️ True print(is_ascii('')) # 👉️ True print(is_ascii('ab фг')) # 👉️ False

我们使用 try/except/else 语句来检查字符串是否仅包含 ASCII 字符。

try 语句使用 str.encode() 方法将字符串编码为 ASCII 编码的字节。

str.encode 方法将字符串的编码版本作为字节对象返回。 默认编码为 utf-8。

如果字符串无法使用 ASCII 编码编码为字节,则会引发 UnicodeEncodeError 并在 except 块中进行处理。

如果 str.encode() 方法成功运行,则不会引发错误并且 else 块运行。

或者,我们可以使用 all() 函数。

使用 all() 检查字符串是否为 ASCII

要检查字符串是否为 ASCII:

使用生成器表达式迭代字符串。检查每个字符的 Unicode 码位是否小于 128。如果所有字符都满足条件,则字符串为 ASCII。 def is_ascii(string): return all(ord(char)


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有