反转句子中的特定字符串

时间:2020-06-15 14:16:20

标签: python

我不明白我哪里出了错

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

示例:

>>> spinWords( "Hey fellow warriors" )
"Hey wollef sroirraw"
>>> spinWords( "This is a test")
"This is a test"
>>> spinWords( "This is another test" )
"This is rehtona test"
def spin_words(sentence):
    split_sentence = sentence.split(" ")
    new_sentence = ""
    for i in split_sentence:
        if len(i) >= 5:
            new_sentence += (i[::-1])
        else:
            new_sentence += i
        if split_sentence.index(i) + 1 < len(split_sentence):
            new_sentence += " "
    return new_sentence

print(spin_words("only sgnirtS rettel the sgnirtS will desrever or a but only will "))

这是我的解决方案,但是代码战有时会说我没有通过测试,并以此为理由。

'etirW gnirts sgnirtS a secapS but sdrow secaps secaps etirW a word this but tsisnoc noitcnuf the desrever snruter sekat same name this rettel this or more more '应该等于'etirW gnirts sgnirtS a secapS but sdrow secaps secaps etirW a word this but tsisnoc noitcnuf the desrever snruter sekat same name this rettel this or more more'

3 个答案:

答案 0 :(得分:1)

您添加空格的方法是错误的:

split_sentence.index(i) + 1 < len(split_sentence)

list.index()给出了该单词的首次出现,因此,如果该单词出现不止一次,则在不出现时为真。

不要手动加入空格。请改用' '.join()

def spin_words(sentence):
    split_sentence = sentence.split(" ")
    new_words = []
    for word in split_sentence:
        if len(word) >= 5:
            new_words.append(word[::-1])
        else:
            new_words.append(word)
    return ' '.join(new_words)

通过FWIW,我会使用一种理解:

def spin_words(sentence):
    words = sentence.split(' ')
    new_words = [w[::-1] if len(w) >= 5 else w for w in words]
    return ' '.join(new_words)

答案 1 :(得分:0)

'etirW sgnirts a secaps,sdrow secaps secaps etirw this这个词,但tsisnoc noitcnuf称呼这个鼻涕虫sekat,这个名字等于或大于'应该等于'etirW gnirts snirrtS secaps,但是d缩secaps tsisnoc noitcnuf毁灭者sekat的名字与该rettel相同或更多。

它告诉您在句子末尾添加一个额外的空格。您插入空格的方式是错误的。如果在开头,结尾或单词之间有更多空格,则所有结果均将失败。

答案 2 :(得分:-1)

尝试一下,

  def spinwords(inp):
    l1 = []
    a=inp.split(' ')
    b=''
    for i in a:
        if len(i)>4:
            i=i[::-1]
            b+=i+" "
        else:
            b+=i+" "
    return b
user = input('Say a phrase:')
print(spinwords(user))

i[::-1]反转字符串。

输出:

Say a phrase:I love stackoverflow
I love wolfrevokcats 

希望这对您有帮助!