Python Forum
Reverse word - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Reverse word (/thread-15701.html)



Reverse word - xSphere - Jan-28-2019

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?


RE: Reverse word - mlieqo - Jan-28-2019

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'



RE: Reverse word - perfringo - Jan-28-2019

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?


RE: Reverse word - xSphere - Jan-28-2019

(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!


RE: Reverse word - perfringo - Jan-28-2019

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



RE: Reverse word - chesschaser - Jul-02-2020

Cleaner

print(string[::-1])



RE: Reverse word - pyzyx3qwerty - Jul-02-2020

(Jul-02-2020, 04:00 PM)chesschaser Wrote: Cleaner

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