Reverse each word in a 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):
  for word in list:
  return reverseWord 
Asked By: Neal Wang



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'
Answered By: NPE
def reversed_words(sequence):
    return ' '.join(word[::-1] for word in sequence.split())

>>> s = "The dog ran"
>>> reversed_words(s)
... 'ehT god nar'
Answered By: Rob Cowie
def reverse_words(sentence):        
     return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" ")))
Answered By: A.Raouf

Another way to go about it is by adding a space to your words reverseWord=reverseWord+word+" " and removing the space at the end of your output by using .strip()

def reverse_words(str):
  reverseWord = ""
  list = str.split()
  for word in list:
    word = word[::-1]
    reverseWord = reverseWord + word + " "
  return reverseWord.strip()

check out this post on how it’s used

Answered By: Moses Okemwa
name=input('Enter first and last name:')
for n in name.split():
    print(n[::-1],end=' ')
Answered By: sanx84

Here is a solution without using join / split :

def reverse(sentence):
    answer = ''
    temp = ''
    for char in sentence:
        if char != ' ':
            temp += char
        rev = ''
        for i in range(len(temp)):
            rev += temp[len(temp)-i-1]
        answer += rev + ' '
        temp = ''
    return answer + temp
reverse("This is a string to try")
Answered By: ssulav

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

>>> import re
>>> s = "The ntdog tnran"
>>> " ".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:[len(], s)
'Teh god nar'
Answered By: RMPR
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.