用一個回傳字串的字串引數撰寫一個函式 fun(long string)。該函式應提取由單個空格“ ”分隔的單詞,排除/洗掉空單詞以及等于“end”和“exit”的單詞,將剩余單詞轉換為大寫,將它們與連接標記字串連接“;” 并回傳這個新加入的字串。我的代碼是......
def fun(long_string): long_string = long_string.split(' ')
try:
if 'exit' in long_string:
long_string.remove('exit')
elif 'end' in long_string:
long_string.remove('end')
except ValueError:
pass
....... 但它并沒有洗掉“結束或退出”。有人可以幫我把它弄出來。我是 python 初學者,我在這里堆疊
uj5u.com熱心網友回復:
你可以試試這個并function按照你的意愿轉換成- 這非常簡單。
代碼沒有完全測驗尚未 (但適用于你的輸入),所以請嘗試不同的輸入和你可以學習“提高”,它能夠滿足您的要求。如果您有任何問題,請提問。
inputs = "this is a long test exit string"
stop_words = ('end', 'exit')
outs = ''
for word in inputs.split():
if word in stop_words:
outs = inputs.replace(word, " ")
ans = ';'.join(w.upper() for w in outs.split()) # do the final conversion
確認它:
assert ans == "THIS;IS;A;LONG;TEST;STRING" # silent means True
編輯:添加功能:
def fun(long_string):
#s = "this is a long test exit string"
stop_words = ('end', 'exit')
outs = ''
for word in long_string.split():
if word in stop_words:
outs = long_string.replace(word, " ")
ans = ';'.join(w.upper() for w in outs.split())
return ans
text = "this is a long test exit string"
print(fun(text))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345569.html
