Python统计字符串信息时如何将空格排除在特殊字符计数外
问题原因
你当前统计特殊符号的逻辑是用字符串总长度减去大小写字母数量、数字数量,空格既不属于大小写字母也不属于数字,所以被默认归类到特殊符号里了。同时你现有代码还存在两处潜在问题:
- 辅音统计逻辑错误:辅音判断条件里误写了
a not in "AEIOUaeiou",其中a是整个输入字符串,应该替换为当前遍历的字符b,否则辅音计数会不准 - 小写字母输出的拼写错误:
lowerrcase多写了一个r
修改方案
只需要在计算scount的时候减去空格的数量,同时修复上述两处问题即可,修改后的完整代码如下:
def calc(): ucount=lcount=dcount=vcount=ccount=0 a = input("Enter the statement :") for b in a: if b.isupper(): ucount+=1 elif b.islower(): lcount+=1 elif b.isdigit(): dcount+=1 for b in a: # 修复辅音判断的变量错误,同时调整逻辑优先级避免判断出错 if (b>="a" and b<="z" or b>="A" and b<="Z") and b not in "AEIOUaeiou": ccount+=1 elif b in "AEIOUaeiou": vcount+=1 b = a.split() wcount=len(b) c = ucount+lcount+dcount # 减去空格数量,将空格从特殊符号统计中排除 scount= len(a)-c - a.count(' ') return ucount,lcount,dcount,vcount,ccount,scount,wcount u,l,d,v,c,s,w=calc() print("Number of uppercase characters =", u) print("Number of lowercase characters =", l) print("Number of digits=", d) print("Number of vowels =", v) print("Number of consonant =", c) print("Number of words =", w) print("Number of special symbols =", s)
效果验证
用你提供的测试输入My name is Kunal Kumar测试,输出的特殊符号数量会变为0,符合预期。
内容的提问来源于stack exchange,提问作者Warmachine
相关产品推荐
相关产品推荐

