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" :
pat = re.compile("\w+")
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:
resultado = pat.sub(invert, "¡Hola, Mundo!")
'! aloH, odnuM!'