首页 > 解决方案 > 如何从特殊字符中删除空格?

问题描述

所以我正在处理一个有这个问题的python作业: 定义一个接受一个句子的函数并计算其中的字母(分别为上下)、单词、数字、元音、辅音和特殊符号的数量。 我为此编写了以下代码:

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 a 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
    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 lowerrcase 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)

输出即将到来,但问题是它也将我给出的空格作为特殊字符,例如:

Enter the statement :My name is Kunal Kumar
Number of uppercase characters = 3
Number of lowerrcase characters = 19
Number of digits= 0
Number of vowels = 5
Number of consonant = 17
Number of words = 5
Number of special symbols = 4

请帮助我了解如何从特殊字符中删除这些空格。

标签: python

解决方案


只需在a计算之前用空字符串替换字符串中的空格scount

scount= len(a.replace(' ',''))-c

推荐阅读