3 回答

TA貢獻1854條經驗 獲得超8個贊
使用此代碼作為改進
def word_count(str):
count = 1
for i in str:
if (i == ' '):
count += 1
if str[0] == ' ':
count -= 1
if str[-1] == ' ':
count -= 1
print (count)
您的錯誤是因為您計算空格是否從開頭開始或出現在末尾。請注意,您不能傳遞空字符串,""因為它被計算為NONE,并且嘗試對其進行索引將導致錯誤

TA貢獻1875條經驗 獲得超3個贊
問題似乎出在句子前面或后面有空格時。解決此問題的一種方法是使用內置函數“strip”。例如,我們可以執行以下操作:
example_string = " This is a string "
print(example_string)
stripped_string = example_string.strip()
print(stripped_string)
第一個字符串的輸出將是
" This is a string "
第二個字符串的輸出將是
"This is a string"

TA貢獻1859條經驗 獲得超6個贊
您可以執行以下操作:
def word_count(input_str):
return len(input_str.split())
count = word_count(' this is a test ')
print (count)
它基本上刪除了前導/尾隨空格并將短語拆分為列表。
如果您偶爾需要使用循環:
def word_count(input_str):
count = 0
input_str = input_str.strip()
for i in input_str:
if (i == ' '):
count += 1
return count
count = word_count(' this is a test ')
print (count)
添加回答
舉報