python怎样判断中文
要判断一个字符串是否是为中文,可使用正则表达式来匹配中文字符。例如,使用re模块的search函数来判断字符串是否是包括中文字符。
import re
def is_chinese(string):
pattern = re.compile('[u4e00-u9fa5]')
match = pattern.search(string)
if match:
return True
else:
return False
# 示例用法
print(is_chinese("Hello, 你好")) # True
print(is_chinese("Hello World")) # False
上述代码中,通过使用正则表达式[u4e00-u9fa5]
来匹配中文字符。如果字符串中包括任何一个中文字符,则返回True,否则返回False。
TOP