如何在python 3中检查字符串是否为100%ascii [英] How to check if string is 100% ascii in python 3

查看:43
本文介绍了如何在python 3中检查字符串是否为100%ascii的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串

  eng =部落冲突– Google Play上的Android应用"rus =城堡冲突:НоваяЭра-Google Play上的Android应用" 

现在我想通过使用 Python 3 检查字符串是否为英文.

我已经在

所以现在我被困在这里,无法弄清楚如何使其正常工作!请指导我,或者我必须使用另一种方法来确定 String 是否为 English !谢谢

解决方案

与您链接到的萨尔瓦多·达利(Salvador Dali)的 answer 一样,您必须使用try-catch块来检查编码中的错误.

 #-*-编码:utf-8-*-def isEnglish(s):尝试:s.encode('ascii')除了UnicodeEncodeError:返回False别的:返回True 

不过请注意,当我复制并粘贴您的 eng rus 字符串进行尝试时,它们都以 False 出现.重新输入英文字母会返回 True ,所以我不确定这是怎么回事.

i have two strings

eng = "Clash of Clans – Android Apps on Google Play"
rus = "Castle Clash: Новая Эра - Android Apps on Google Play"

and now i want to check whether string is in English or not by using Python 3.

I have read this Stackoverflow answer here and it does not help me as its for Python 2.x solution but in comments some one mention that use

string.encode('ascii')

to make it work in Python 3.x but my problem is, in both cases it raises same UnicodeEncodeError exception!

Screenshot:

so now i am stuck here and cant figure out how to make it work! kindly guide me or i have to use another method to determine if String is in English or not! Thanks

解决方案

As with Salvador Dali's answer you linked to, you must use a try-catch block to check for an error in encoding.

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

Just to note though, when I copy and pasted your eng and rus strings to try them, they both came up as False. Retyping the English one returned True, so I'm not sure what's up with that.

这篇关于如何在python 3中检查字符串是否为100%ascii的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆