我有一個任務,寫一個代碼來計算字符串中的單詞。我還沒有學會分割,所以我不能使用它。我只能使用函數,循環和條件。他故意在字符串中添加了三個額外的空格,我必須弄清楚如何才能將它看作一個字符串。我卡住了。幫幫我!如何讓Python忽略多餘的空格?
def wordCount(myString):
try:
spaceCount = 0
char = ""
for i in myString:
char += i
if char == " ":
spaceCount == 1
pass
elif char == " ":
spaceCount += 1
return spaceCount+1
except:
return "Not a string"
print("Word Count:", wordCount("Four words are here!"))
print("Word Count:", wordCount("Hi David"))
print("Word Count:", wordCount(5))
print("Word Count:", wordCount(5.1))
print("Word Count:", wordCount(True))
馬上蝙蝠,讓我給你一些建議:儘量使你的'嘗試 - 除了'塊封裝了可能/有用的最小代碼量。並且*總是*顯式地捕獲一些錯誤類型,裸體'except'子句可以掩蓋你並不期待的錯誤! –
你怎麼卡住了?什麼是或沒有發生? – wwii
堆棧溢出不是讓人們來解決你的功課,但這裏有一個提示:做一個變量來跟蹤前一個字符。如果你得到一個空間,但最後一個角色也是一個空間,你不知道這個空間。 – dlsso