您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中检测具有非英文字符的字符串

在Python中检测具有非英文字符的字符串

您只需检查字符串是否只能使用ASCII字符(拉丁字母+其他字符)进行编码。如果它不能被编码,则它具有来自其他字母的字符。

注意评论# -*- coding: ....。它应该在python文件的顶部(否则您会收到一些关于编码的错误

# -*- coding: utf-8 -*-
def isEnglish(s):
    try:
        s.encode(encoding='utf-8').decode('ascii')
    except UnicodeDecodeError:
        return False
    else:
        return True

assert not isEnglish('slabiky, ale li?í se podle významu')
assert isEnglish('English')
assert not isEnglish('?? ???????? ?? ?????? ??')
assert not isEnglish('how about this one : 通 asf?')
assert isEnglish('?fd4))45s&')
python 2022/1/1 18:25:54 有510人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶