Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Reverse word
#1
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?
Quote
#2
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'
Quote
#3
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?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote
#4
(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!
Quote
#5
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  print a word after specific word search evilcode1 8 178 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  is there a reverse index? Skaperen 6 463 Jun-14-2019, 11:47 PM
Last Post: Skaperen
  Reading one value from an array in reverse DreamingInsanity 10 602 May-04-2019, 08:14 AM
Last Post: DreamingInsanity
  reverse generator Skaperen 7 3,350 Apr-23-2018, 03:10 AM
Last Post: Skaperen
  difference between word: and word[:] in for loop zowhair 2 887 Mar-03-2018, 07:24 AM
Last Post: zowhair
  Python Speech recognition, word by word AceScottie 5 6,303 Aug-21-2017, 12:37 PM
Last Post: DeaD_EyE

Forum Jump:


Users browsing this thread: 1 Guest(s)