要判断str是什么字符,首先要清楚当前是什么类型。
如果文件开始注释过:#coding: utf-8,那么字符默认就是utf-8
文件开始最好注释,不然会调用系统编码。
以utf-8文件为例,先decode()要判断的str,变成unicode
如果默认是unicode,就可以直接判断,比如:
strs = u”中文”
以u开头本身就是unicode,那么直接判断。
然后:
# coding: utf-8
def is_chinese(uchar):
“””判断一个unicode是否是汉字”””
if uchar >= u’\u4e00′ and uchar<= u’\u9fa5′:
return True
else:
return False
def is_number(uchar):
“””判断一个unicode是否是数字”””
if uchar >= u’\u0030′ and uchar<=u’\u0039′:
return True
else:
return False
def is_alphabet(uchar):
“””判断一个unicode是否是英文字母”””
if (uchar >= u’\u0041′ and uchar<=u’\u005a’) or (uchar >= u’\u0061′ and uchar<=u’\u007a’):
return True
else:
return False
def is_other(uchar):
“””判断是否非汉字,数字和英文字符”””
if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):
return True
else:
return False