Iterate through a string and reverse any word with 5 or more characters – Codewars Kata

Question:

def spin_words(sentence):
        words = sentence.split(' ')
        newwords = []
        reverse = []
        for word in words:
                if len(word) < 5:
                        newwords.append(word)
                elif len(word) >= 5:
                        newword = list(word)
                        for letter in newword:
                                reverse.insert(0, letter)
                        newwords.append(''.join(reverse))
        return ' '.join(newwords)

print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))

Working on a Codewars kata for python. Need to take a string and reverse any words that are 5 or more characters long. This code works for single words, but once more than one word is 5 or more characters, it adds those words together for each following word. Ex: my ‘Hey fellow warriors’ comes back as ‘Hey wollef sroirrawwollef’ . I am just not sure why is is putting different words together and how to fix it. As far as I know, the for loop in the elif should close out for each word. I know it should be simple, just trying to learn what’s happening and why. Thank you!

Asked By: DYIII

||

Answers:

Simple answer:

You have to clear your reversed word:

def spin_words(sentence):
        words = sentence.split(' ')
        newwords = []
        reverse = []
        for word in words:
                if len(word) < 5:
                        newwords.append(word)
                elif len(word) >= 5:
                        newword = list(word)
                        for letter in newword:
                                reverse.insert(0, letter)
                        newwords.append(''.join(reverse))
                        reverse = [] # Clear the list.
        return ' '.join(newwords)

print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))

Output:

emocleW
to
sraWedoC
Hey wollef sroirraw

Nicer answer:

After Ignatius Reilly’s comment I made my solution a bit more elegant:

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

Here is how I reversed the word.

Output is the same.

Answered By: TheShadow75
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.