繁体   English   中英

如何从特殊字符中删除空格?

[英]How to remove spaces from special characters?

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

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)

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

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

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

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

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

您可以使用替换方法

a.replace(" ", "")

请阅读下面的代码

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":
        if b not in "AEIOUaeiou":
            ccount+=1
    if 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

我已经测试过了。

请在检查后提交。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM