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):
return m.group(0)[::-1]
resultado = pat.sub(invert, "¡Hola, Mundo!")
'! aloH, odnuM!'