[6 kyu] Your order, please

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Examples

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""

Solution :

def order(sentence):
    list_word = []
    new_list = []
    count = 0
    list_number = ["1","2","3","4","5","6","7","8","9"]

    new_sentence = ""
    list_word = sentence.split()
    for word in list_word:
        new_list.append(word)

    for word in list_word:

        for letter in word:

            if letter in list_number:

                new_list[int(letter) - 1] = word

    for new_word in new_list:
        if count <= len(new_list) - 2:
            new_sentence += new_word + " "
            count += 1

    if len(list_word) != 0:
        new_sentence = new_sentence + new_list[len(new_list)-1]
  # code here
    return new_sentence
发布了16 篇原创文章 · 获赞 0 · 访问量 51

猜你喜欢

转载自blog.csdn.net/HM_773_220/article/details/104764145