我的任務是撰寫一個帶有一個字串引數的函式,該函式回傳一個字串。該函式應提取此字串中的單詞,洗掉空單詞以及等于“end”和“exit”的單詞,將剩余單詞轉換為大寫,并使用連接標記字串“;”將它們連接起來。并回傳這個新加入的字串。
這是我的函式,但如果字串不包含單詞“exit”或“end”,則不會回傳新字串:
def fun(long_string):
stop_words = ('end', 'exit', ' ')
new_line = ''
for word in long_string:
if word in stop_words:
new_line = long_string.replace(stop_words, " ")
result = ';'.join(new_line.upper())
return result
print(fun("this is a long string"))
uj5u.com熱心網友回復:
的條件if是 never True,因為word它不是一個真正的“詞”;word在您的代碼中將是long_string. 那么,if確實這里比較't'有'end'等等。因此,new_line始終保持為初始化時的空字串。
您將需要split使用單詞:
def fun(long_string):
return ';'.join(word for word in long_string.split() if word not in ('end', 'exit'))
print(fun("this is a long string")) # this;is;a;long;string
您不需要檢查空詞,因為split將它們視為分隔符(即,甚至不是一個詞)。
uj5u.com熱心網友回復:
for word in long_string將遍歷 中的每個字符long_string,而不是每個單詞。下一行將每個字符與 中的單詞進行比較stop_words。
您可能想要類似的東西for word in long.string.split(' ')來迭代單詞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/367021.html
