9

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 
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
Neal Wang
  • 1,049
  • 3
  • 10
  • 8

8 Answers8

14

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'
NPE
  • 464,258
  • 100
  • 912
  • 987
4
def reversed_words(sequence):
    return ' '.join(word[::-1] for word in sequence.split())

>>> s = "The dog ran"
>>> reversed_words(s)
... 'ehT god nar'
Rob Cowie
  • 21,692
  • 6
  • 61
  • 56
1
def reverse_words(sentence):        
     return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" ")))
A.Raouf
  • 1,951
  • 1
  • 23
  • 32
1

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

Moses Okemwa
  • 143
  • 6
1
name=input('Enter first and last name:')
for n in name.split():
    print(n[::-1],end=' ')
sanx84
  • 11
  • 1
  • 3
    In general "code only" answers are considered to be bad practice. Please open up a little bit what your code does and how it helps to solve the problem. – quinz Sep 20 '17 at 11:53
1

Below program without using join / split :

def reverse(sentence):
    answer = ''
    temp = ''
    for char in sentence:
        if char != ' ':
            temp += char
            continue
        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")
ssulav
  • 61
  • 4
1

x = input("Enter any sentence :: :: ")

y = x.split(' ')

for i in y :

r = i[::-1]
print(r,end=" ")
adityaB
  • 11
  • 1
  • 2
1

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'
RMPR
  • 3,104
  • 3
  • 18
  • 29