I wrote a program to reverse the words in a given sentence here:
def rev_each_word_in(Sentence):
print(' '.join(Word[::-1] for Word in Sentence.split()))
As my input for Sentence I used "to be or not to be that is the question." This returns the following:
ot eb ro ton ot eb taht si eht .noitseuq
It's almost exactly what I want, but is there a way that the period could remain at the end of the sentence, so the return would be:
ot eb ro ton ot eb taht si eht noitseuq.
Here comes some ugliness that takes care of this in one line:
from string import punctuation as p
print(' '.join(w[::-1] if w[-1] not in p else w[:-1][::-1] + w[-1] for w in Sentence.split()))
Where we reverse fully if the last character in a word is not in the punctuation string and if it is we reverse the string up until the punctuation and then add the punctuation to it. prints out:
ot eb ro ton ot eb taht si eht noitseuq.
Slimming it down as much as I can because I'm ashamed of it:
# similar to [::-1]
r = slice(None, None,-1)
# cut down chars!
l = Sentence.split()
# reverse condition too and use shorter names
print(' '.join(w[:-1][r] + w[-1] if w[-1] in p else w[r] for w in l))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With