鱼C论坛

 找回密码
 立即注册
查看: 6206|回复: 1

[已解决]请教大家,为什么python中isalpha()函数会把汉字判定为字母?

[复制链接]
发表于 2017-7-25 11:28:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
零基础学习python19课练习题
def count(*param):
    length = len(param)
    for i in range(length):   
        letters = 0
        space = 0
        digit = 0
        other = 0
        for each in param[i]:
            if each.isalpha():
                letters += 1
            elif each.isdigit():
                digit += 1
            elif each ==  " ":
                space += 1
            else:
                other += 1
        print("第%d个字符串有:英文字母%d个,空格%d个,数字%d个,其他字符%d个"%(i+1,letters,space,digit,other))

count("汉字")
最佳答案
2017-7-25 12:09:11
对于unicode string,string.isalpha会根据字符串中的字符是否属于Unicode编码的LETTER区域来判断是否都由字母组成。所以得出的结果为True,不一定表示只有26个英文字母。
  1. def count(*param):
  2.     length = len(param)
  3.     for i in range(length):   
  4.         letters = 0
  5.         space = 0
  6.         digit = 0
  7.         other = 0
  8.         for each in param[i]:
  9.             print(each)
  10.             if each.encode('UTF-8').isalpha():
  11.                 letters += 1
  12.             elif each.encode('UTF-8').isdigit():
  13.                 digit += 1
  14.             elif each ==  " ":
  15.                 space += 1
  16.             else:
  17.                 other += 1
  18.         print("第%d个字符串有:英文字母%d个,空格%d个,数字%d个,其他字符%d个"%(i+1,letters,space,digit,other))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-7-25 12:09:11 | 显示全部楼层    本楼为最佳答案   
对于unicode string,string.isalpha会根据字符串中的字符是否属于Unicode编码的LETTER区域来判断是否都由字母组成。所以得出的结果为True,不一定表示只有26个英文字母。
  1. def count(*param):
  2.     length = len(param)
  3.     for i in range(length):   
  4.         letters = 0
  5.         space = 0
  6.         digit = 0
  7.         other = 0
  8.         for each in param[i]:
  9.             print(each)
  10.             if each.encode('UTF-8').isalpha():
  11.                 letters += 1
  12.             elif each.encode('UTF-8').isdigit():
  13.                 digit += 1
  14.             elif each ==  " ":
  15.                 space += 1
  16.             else:
  17.                 other += 1
  18.         print("第%d个字符串有:英文字母%d个,空格%d个,数字%d个,其他字符%d个"%(i+1,letters,space,digit,other))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-18 10:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表