One-liner to reverse a String on a word basis
Browsing Lobsters, I stumbled upon a thread, someone
talking about reversing a string on a word basis using C while in retrospect they could just have used awk
.
I decided to give it a shot but make it more challenging by using a one-liner. Once again I am amazed by the
power of the coreutils, it almost feels like cheating:
tr " " "\n" | awk '/^\S+$/' | rev | tr "\n" " "
But I’m afraid the poster was wrong, the Python version is shorter:
" ".join(x[::-1] for x in s.split())
It’s probably even shorter in Perl, but I don’t know enough of it to compare.
Written on April 2, 2021