Python Forum

Full Version: Reverse word
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!
I need to reverse words like this:
cake
python
Output:
keca onthpy
I used [::-1] but this isn't a correct answer because it gives me:
cake
python
Output:
ekac nohtyp
Any suggestion?
there is for sure much cleaner way but for now :) :
n = 2    # num of chars 
s = ''.join([line[i:i+n] for i in range(0, len(line), n)][::-1])
with line being your string.
First you create a list out of every n number of characters, then you reverse the list and join the elements into string again.

cake:
Output:
'keca'
python:
Output:
'onthpy'
You should specify your task more precisely. It's not obvious what are the exact requirements. It seems that there should be two letter chunks from word and they should be in reverse order.

cake -- > ca ke --> ke ca
python --> py th on --> on th py


Do words have always even number of characters?
(Jan-28-2019, 09:15 AM)mlieqo Wrote: [ -> ]there is for sure much cleaner way but for now :) :
n = 2    # num of chars 
s = ''.join([line[i:i+n] for i in range(0, len(line), n)][::-1])
with line being your string.
First you create a list out of every n number of characters, then you reverse the list and join the elements into string again.

cake:
Output:
'keca'
python:
Output:
'onthpy'

THANKS! This works!
There is built-in module textwrap which can be used to get desired results:

>>> from textwrap import wrap
>>> a = 'python'
>>> ''.join(reversed(wrap(a, width=2)))         # [::-1] can be used instead of reversed
onthpy
Just for fun: inefficient mental exercise :

>>> a = 'python'
>>> ''.join([a[a.index(x):a.index(x) + 2] for x in a][::2][::-1])
onthpy
Cleaner

print(string[::-1])
(Jul-02-2020, 04:00 PM)chesschaser Wrote: [ -> ]Cleaner

print(string[::-1])
This doesn't work for him like he already said, @chesschaser