新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python怎么判断中文,python如何判断中文字符

发布时间:2024-01-17 04:42:45

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。