Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing words in a Python string (including punctuation)

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.
like image 659
maio123maio Avatar asked May 26 '26 18:05

maio123maio


1 Answers

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))
like image 154
Dimitris Fasarakis Hilliard Avatar answered May 28 '26 08:05

Dimitris Fasarakis Hilliard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!