在Python中,判断一个字符或字符串是否为中文,可以通过以下几种方法:
1. 使用Unicode编码范围:
def is_chinese(char):return u'\u4e00' <= char <= u'\u9fff'
2. 使用`unicodedata`库:
import unicodedatadef is_chinese(char):return 'CJK' in unicodedata.name(char)
3. 使用正则表达式:
import redef is_chinese(word):pattern = re.compile(r'[\u4e00-\u9fff]+')return bool(pattern.match(word))
4. 借助GB2312或GBK字符集:
def is_chinese_gb(word):return len(word) == len(word.encode('gb2312'))
5. 判断字符串是否全是中文:
def is_all_chinese(strs):for char in strs:if not u'\u4e00' <= char <= u'\u9fff':return Falsereturn True
6. 判断字符串是否包含中文:
def check_contain_chinese(check_str):for ch in check_str:if u'\u4e00' <= ch <= u'\u9fff':return Truereturn False

