How to invert individual words of a string with python?


I want to invert the string but I keep the word order and only invert the letters as for example, if I have


My dog Renzo

I should get


iM orrep ozneR.

But when I use [::-1] it gives me this result:


ozneR orrep iM

How can I avoid inverting the words?

print (("Mi perro Renzo")[::-1])
asked by Jorge Barcos 07.09.2018 в 01:54

3 answers


A more powerful and robust way would be using regular expressions . To locate words we can use the pattern '\w+' , which comes to indicate "any set of letters, excluding punctuation marks and spaces" :

import re

pat = re.compile("\w+")
print(pat.findall("¡Hola, Mundo!")

['Hello', 'World']

Note that the method of dividing the sentence according to the spaces would have given us the comma ',' and the exclamations '¡!' as part of words.

The result of the regular expression can be used to directly modify the string, saving us from doing more operations. Just pass a function that reverses each of the words found:

def invert(m):

resultado = pat.sub(invert, "¡Hola, Mundo!")

'! aloH, odnuM!'

answered by 07.09.2018 / 12:03

You could try to separate the words by spaces, then invert them with [::-1] and finally put them back together.

Like this:

' '.join([x[::-1] for x in ("Mi perro Renzo").split(' ')])

First, we separate everything into an array with ("Mi perro Renzo").split(' ') :

['Mi', 'perro', 'Renzo']

Then to each element of the arrangement we apply the inversion [x[::-1] for x in ("Mi perro Renzo").split(' ')] , resulting:

['iM', 'orrep', 'ozneR']

And finally with ' '.join(...) we re-link everything for a blank space.

answered by 07.09.2018 в 02:17

Try this

def reverse(phrase):
    return ' '.join(list(map(lambda x: x[::-1], phrase.split())))

print(reverse("Mi perro Renzo"))


>>> iM orrep ozneR
answered by 07.09.2018 в 02:29