[英]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.