1. 任務
由題目可以知道,任務是根據字符串中的單詞夾帶的數字對字符串進行重新排序。
例如:
排序前:“is2 Thi1s T4est 3a”
排序後:“Thi1s is2 3a T4est”
2.思路
我的思路是:
- 將整個字符串先分割,做成一個單詞(word)爲元素的 list
- 對每一個 word ,找到它包含的數字,並記錄到輔助 list 中
- 根據輔助 list 和 words 構成的 list ,從小到大排序並重新構成一個新的字符串
3. 代碼
def order(sentence):
if sentence == "":
return ""
# 分割字符串並定義輔助函數
words = sentence.split(' ')
indexs = []
result = ""
# 找到並記錄每個單詞中的數字
for word in words:
for w in word:
if w.isnumeric():
indexs.append(int(w))
for i in range(1,len(words)+1):
ind = indexs.index(i)
result = result + words[ind] + " "
return result.rstrip()