Invert every word in a string

I have a little problem in my code. I am trying to change the words and character of a string. For example, "the dog ran," would become "ehT god nar"

The code is almost working. 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 
+4
source share
7 answers

You are on the right track. The main problem is that "" is an empty line, not a space (and even if you fix it, you probably won't want a space after the last word).

Here's how you can do it more briefly:

 >>> s='The dog ran' >>> ' '.join(w[::-1] for w in s.split()) 'ehT god nar' 
+9
source
 def reversed_words(sequence): return ' '.join(word[::-1] for word in sequence.split()) >>> s = "The dog ran" >>> reversed_words(s) ... 'ehT god nar' 
+3
source
 def reverse_words(sentence): return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" "))) 
0
source

Another way to do this is by adding a space to your words reverseWord=reverseWord+word+" " and removing the space at the end of the output with .strip()

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

read this post on how it is used

0
source
 name=input('Enter first and last name:') for n in name.split(): print(n[::-1],end=' ') 
0
source

Below are the programs 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") 
0
source

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

y = x.split ('')

for I am in you:

 r = i[::-1] print(r,end=" ") 
0
source

Source: https://habr.com/ru/post/1385671/


All Articles