Python 判断字符串是否包含中文

骑猪看日落 2021-11-22 17:10 961阅读 0赞

一、摘要

使用 xlrd 模块打开带中文的excel文件时,会报错。

  1. FileNotFoundError: [Errno 2] No such file or directory: 'xx.xlsx'

这个时候,就需要检测文件名,是否包含中文,及时return。

二、原理

中文字符的编码范围是:

  1. \u4e00 - \u9fff

只要编码在此范围就可判断为中文字符

三、函数

  1. def is_chinese(self, string):
  2. """
  3. 检查整个字符串是否包含中文
  4. :param string: 需要检查的字符串
  5. :return: bool
  6. """
  7. for ch in string:
  8. if u'\u4e00' <= ch <= u'\u9fff':
  9. return True
  10. return True

本文参考链接:

https://segmentfault.com/a/1190000017940752?utm_source=tag-newest

发表评论

表情:
评论列表 (有 0 条评论,961人围观)

还没有评论,来说两句吧...

相关阅读