为了账号安全,请及时绑定邮箱和手机立即绑定

如何检查Python中的字符串是否为ASCII?

如何检查Python中的字符串是否为ASCII?

狐的传说 2019-09-19 14:27:26
我想检查一个字符串是否是ASCII格式。我知道ord(),但是当我尝试时ord('é'),我有TypeError: ord() expected a character, but string of length 2 found。我知道它是由我构建Python的方式引起的(如ord()文档中所述)。还有其他方法可以检查吗?
查看完整描述

3 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

def is_ascii(s):

    return all(ord(c) < 128 for c in s)


查看完整回答
反对 回复 2019-09-19
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

我想你不是在问正确的问题 -


python中的字符串没有与'ascii',utf-8或任何其他编码对应的属性。你的字符串的来源(无论你是从文件中读取,从键盘输入等)都可能在ascii中编码了一个unicode字符串来生成你的字符串,但这就是你需要去寻找答案的地方。


也许你可以问的问题是:“这个字符串是在ascii中编码unicode字符串的结果吗?” - 您可以通过尝试来回答:


try:

    mystring.decode('ascii')

except UnicodeDecodeError:

    print "it was not a ascii-encoded unicode string"

else:

    print "It may have been an ascii-encoded unicode string"


查看完整回答
反对 回复 2019-09-19
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

Python 3方式:


isascii = lambda s: len(s) == len(s.encode())

要检查,请传递测试字符串:


str1 = "♥O◘♦♥O◘♦"

str2 = "Python"


print(isascii(str1)) -> will return False

print(isascii(str2)) -> will return True


查看完整回答
反对 回复 2019-09-19
  • 3 回答
  • 0 关注
  • 2509 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信