Home > OS >  Error trying reversing words in a string using python
Error trying reversing words in a string using python

Time:01-27

def spin_words(sentence):
    for word in sentence.split():
        if len(word)>=5:
            words = word[::-1]
    new_sentence = sentence.replace(word,words) 
    return new_sentence
spin_words('Hey fellow warriors')


#output is 'Hey fellow sroirraw'

i'm trying to reverse some words in a string that are greater than five characters but i only get one word reversed.

CodePudding user response:

It is easier to store the sentence as an array and change each element independently than modifying the entire sentence on each iteration.

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

rev = spin_words('Hey fellow warriors')
print(rev)  # Hey wollef sroirraw

Note: This solution does not preserve consecutive spaces or newlines.

CodePudding user response:

You should e.g. move the reversal into the loop itself:

def spin_words(sentence):
    for word in sentence.split():
        if len(word)>=5:
            words = word[::-1]
            sentence = sentence.replace(word, words) 
    return sentence

spin_words('Hey fellow warriors')

You should also be wary of words being parts of other words, e.g. in tester anothertester.

CodePudding user response:

Try this for your code:

def spin_word(this_word):
    rotated_list = list(this_word.lower())[::-1]
    rotated_word = ''.join(rotated_list)
    return rotated_word

def spin_frase(frase):
    rotated_frase = []
    for word in frase.split():
        if len(word) >= 5:
            rotated_frase.append(spin_word(word))
        else:
            rotated_frase.append(word)
    print(' '.join(rotated_frase))

if __name__ == '__main__':
    spin_frase('Hey fellow warriors')
  • Related