最近有判斷字符串是否是中文的需求,就網上看見了一篇一萬多閱讀的帖子,發現其中存在一些邏輯錯誤。
python判斷字符串是否是中文
def is_Chinese(word):#修改過的
for ch in word:
if '\u4e00' > ch or ch > '\u9fff':
return False
return True
def is_Chinese1(word):#原版
for ch in word:
if '\u4e00' <= ch <= '\u9fff':
return True
return False
print(is_Chinese("測試"))
print(is_Chinese1("測試"))
輸出:
True
True
現在看起來是否並沒有什麼錯誤。可是
print(is_Chinese("測ac"))
print(is_Chinese1("測ac"))
輸出:
False
True
相信你們已經知道爲什麼了吧!就是他的這個代碼只是測了一下第一個字是不是漢字,但是對於後面的就不管了。所以他設計的這個代碼並不能達到我們所期望的需求。