This is because the entire content of frase
is reversed, since the Slice [::-1]
operates over the entire string. If you want each word of the phrase to be reversed individually, you need to separate the phrase into words, invert each word and then join them together.
For this, just use the method split
to separate the phrase into words. Assuming that the words are separated only by spaces, simply call the method without arguments (frase.split()
), that it will return a list of strings, in which each element is one of the words.
Then you invert each word individually and put it back together. You can make a traditional loop as per the jean’s answer (although its solution leaves an extra space at the end), but can also use the method join
, along with a comprehensilist on, which is a much more succinct and pythonic:
frase = input('Digite uma frase: ')
print(' Você digitou: {}'.format(frase))
invertida = ' '.join(palavra[::-1] for palavra in frase.split())
print('A frase que você digitou invertida fica: {}'.format(invertida))
In the case, the join
joins the list elements, using the space (' '
) as a separator. The palavra[::-1] for palavra in frase.split()
within the join
is the comprehensilist on, which is another way to write a loop similar to that of jean’s answer. Basically, for every word resulting from split
, the inversion of this is done individually, and in the end the join
put them all together.
Note also that the function input
already returns a string, so you don’t need to call str(input(...))
, is redundant.
We could stop here, but there is a detail in this implementation. If we have a phrase like the example below:
frase = 'Oi, tudo bem? Blablabla'
invertida = ' '.join(palavra[::-1] for palavra in frase.split())
print(invertida)
The result is:
,iO odut ?meb albalbalB
Note that the comma and question mark were also reversed (because the division was made by the spaces, so the characters ,
and ?
were considered part of the words. And the various spaces before "Blablabla" were exchanged for only one. This happens because the split
separated by several spaces, but in join
I only used one (this case would solve using frase.split(' ')
, but the comma and the question mark would remain part of the inversion).
In this case you could use regular expressions (regex), through the module re
. A regular expression also has the method split
, but it can use more complex criteria, which allow to treat these cases:
import re
def inverte(palavra):
if re.match(r'^\w+$', palavra):
return palavra[::-1]
return palavra
frase = 'Oi, tudo bem? Blablabla'
invertida = ''.join(inverte(palavra) for palavra in re.split(r'(\W+)', frase))
print(invertida)
In the split
used (\W+)
. The \W
is a shortcut for "non-alphanumeric character" (anything that nay be it letter, number or _
). The +
is a quantifier meaning "one or more occurrences". That is, I am separating the sentence not only by spaces, but by any non-alphanumeric characters.
Moreover, the parentheses form a capture group. And when there are capture groups in regex, separators are also returned in the list. So I don’t lose the original values that the phrase had (the list returned by split
will have the words and separators), and I can restore them when it comes to putting everything together at the end.
Then I use the comprehensilist on, but with an auxiliary function I created to know if what I have is actually a word, or a separator (the comma, the ?
, spaces, etc). For this I use ^\w+$
: the markers ^
and $
are respectively the beginning and end of the string, and \w+
is "one or more alphanumeric characters".
So, if it is a word (if it only has alphanumeric characters from the beginning to the end of the string), I invert it. Otherwise, I leave it as is.
In the end, I put it all together join
(but now I’ve used the empty string ''
instead of space ' '
). The result is:
iO, odut meb? albalbalB
Now only the words have been reversed. The spaces and scores have been kept intact.
Of course, you can always make it harder. If the string has emojis, or even some accented characters, depending on the case, a simple inversion like this may not work. Then maybe it’s too far from the scope of the question, but it’s interesting to take a look in this answer to understand more details about these cases (although the answer is in Java, there are some more general concepts about Unicode, which apply to other languages, including Python).
You can apply the
split()
and then invert each element of the generated array and just print– Tmilitino
I tried to use split(), but it was just what I could not, it prints the phrase cm words separated by quotation marks and does not reverse the order of letters, only the order of words, I did not understand precisely how I would use it.
– Luiz Rodrigues