Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse each word in a string

Tags:

python

string

I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar"

The code almost works. It just does not add spaces. How would you do that?

def reverseEachWord(str):
  reverseWord=""
  list=str.split()
  for word in list:
    word=word[::-1]
    reverseWord=reverseWord+word+""
  return reverseWord 
like image 664
Neal Wang Avatar asked Dec 10 '11 17:12

Neal Wang


2 Answers

You are on the right track. The main issue is that "" is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word).

Here is how you can do this more concisely:

>>> s='The dog ran'
>>> ' '.join(w[::-1] for w in s.split())
'ehT god nar'
like image 188
NPE Avatar answered Oct 06 '22 11:10

NPE


You can also deal with noise in the string using the re module:

>>> import re
>>> s = "The \n\tdog \t\nran"
>>> " ".join(w[::-1] for w in re.split(r"\s+", s))
'ehT god nar'

Or if you don't care:

>>> s = "The dog ran"
>>> re.sub(r"\w+", lambda w: w.group(0)[len(w.group(0))::-1], s)
'Teh god nar'
like image 41
RMPR Avatar answered Oct 06 '22 11:10

RMPR