一、請寫一個 Python 語言函式(function),reverse_sentence(s),回傳所傳 送進去的字串,逐字翻轉(reverse)結果。例如 reverse_sentence(“abc def”) 回傳“def abc”。(20 分)
詳解 (共 4 筆)
d0172533
詳解 #3673625
def reverse_order(se...
(共 76 字,隱藏中)
前往觀看
hchungw
詳解 #6136169
def reverse_sentence(s):
# 將字串分割成單詞列表
words = s.split()
# 反轉單詞列表
reversed_words = words[::-1]
# 將反轉後的單詞列表重新組合成字串並回傳
return ' '.join(reversed_words)
# 將字串分割成單詞列表
words = s.split()
# 反轉單詞列表
reversed_words = words[::-1]
# 將反轉後的單詞列表重新組合成字串並回傳
return ' '.join(reversed_words)
# 測試範例
print(reverse_sentence("abc def")) # 輸出: "def abc"
print(reverse_sentence("Hello World")) # 輸出: "World Hello"
這個函式首先將輸入的字串按空格分割成單詞列表,然後將這個列表反轉,最後將反轉後的單詞列表重新組合成字串並回傳。
print(reverse_sentence("abc def")) # 輸出: "def abc"
print(reverse_sentence("Hello World")) # 輸出: "World Hello"
這個函式首先將輸入的字串按空格分割成單詞列表,然後將這個列表反轉,最後將反轉後的單詞列表重新組合成字串並回傳。
Liao Ping Lun
詳解 #5587351
# 解法 # 將字串以空白切割後,存到串...
(共 326 字,隱藏中)
前往觀看
蔡佳怡
詳解 #5485215
def reverse_sentence(s):
list=s.split(' ') #將字串以空格分割,並存入list,list為['abc','def']
return ' '.join(list[::-1]) #[::-1]將list裡的元素反轉,而' '.join是以空格合併反轉後list裡的元素