题目

Stop gninnipS My sdroW!

不要扭曲我的话语

描述

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

编写一个函数,该函数接受一个或多个单词的字符串,并返回相同的字符串,但所有五个或多个字母单词都颠倒(就像这个Kata的名称一样)。传入的字符串将仅由字母和空格组成。只有存在多个单词时,才会包含空格。

举例

spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"

思路

首先明白,我们使用python解题的话,不好直接操作字符串,可以先进行转换,正好这里是对单个的单词进行翻转,所以想到了将这个字符串按照空格的方式拆分,使用split

然后就好操作,直接遍历每一个单词,看这个单词的长度是否是大于等于5,如果是就翻转,这里可以直接使用切片[::-1],但是为了好理解,我先进行了拆分,然后再翻转

最后拆分的结果,组合成字符串即可,注意这里使用空格隔开

完整代码

def spin_words(sentence):
    # Your code goes here
    # 首先根据空格拆分成单个的单词
    sentence = sentence.split(' ')
    # 遍历,去判断每个单词是否需要翻转
    for i in range(len(sentence)):
        # 如果单词长度大于等于5,说明需要翻转
        if len(sentence[i]) >= 5:
            # 因为python不能直接对字符串进行操作,所以需要先转换成列表
            val = list(sentence[i])
            # 翻转
            val.reverse()
            # 合并成字符串
            sentence[i] = "".join(val)
    # 合并成最终的结果,注意这里需要空格隔开
    return " ".join(sentence)