判断字符串中是否又汉字,一般是判断字符是否在范围 [ u'\u4e00' , u'\u9fa5' ] 之内,但是在与python3 的isalpha()函数(检测字符串中是否只有字符组成)一起判断时,需要注意,isalpha()方法判断汉字时也返回True!
所以,在判断是否是字母之前,需要先判断汉字,否则汉字将作为字母统计!
"""
!/usr/bin/env python3.6
-*- coding: utf-8 -*-
--------------------------------
Description :
--------------------------------
@Time : 2018/11/26 14:27
@File : test.py
@Software: PyCharm
--------------------------------
@Author : lixj
@contact : [email protected]
"""
# 输入一行字符,分别统计出其中 中文、英文字母、空格、数字和其它字符的个数
def countNum(string):
result = [0, 0, 0]
for char in string:
if u'\u4e00' <= char <= u'\u9fa5': # 判断是否是汉字,在isalpha()方法之前判断
result[0] += 1
elif char.isalpha(): # !汉字也返回true
result[1] += 1
else:
result[2] += 1
return result
result = countNum("123test 哈哈 #@*")
print(result) # [2, 4, 8]
# 或者采用正则re判断
import re
result = re.compile(u'[u\4e00-\u9fa5]')
con = "哈哈"
if result.search(con):
print(True) # True