Python Forum

Full Version: Reversing word in strings yields unexpected result
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello there, 
I'm recently learning python using python 3.6
I'm confused why the str.join seems not to work properly in my code
there are many examples I've read and I can't find the example using input()

def rev():
   my_input=input("Please input what you want to reverse: ")
   my_output=my_input.split()
   for word in my_output:
       my_output=" ".join(my_output[::-1])
   print(my_output)

rev()
If the input is "Python forum" the output should be "nohtyP murof". However it would yield "n o h t y P   m u r o f", and if I remove the space in the join, it would yield "nohtyPmurof". Help me, I'm stuck on this. Thank you. PS: if you would, please don't use a complex example like doing this whole task in one line, I really am a beginner.
converting to a list, and back to a string is pointless as you can create a new string reversed
>>> s = "Python Forum"
>>> s[::-1]
'muroF nohtyP'
Quote:PS: if you would, please don't use a complex example like doing this whole task in one line, I really am a beginner.
The [::-1] is splicing. in which is [START:STOP:STEP] where any field can be empty. start and stop is empty which means the whole string, -1 for step reversing the whole string. More info here under indexing and splicing
https://python-forum.io/Thread-Basic-Strings

EDIT:
just realized your rev the words as well. Here is how
s = 'Python Forum'
rev_str = s[::-1]
rev_words = rev_str.split()[::-1]
print(' '.join(rev_words))
Yes, but it looks like he wants to keep the words in the same order, just reverse the letters.
My clunky solution:

def rev():
    my_input = input("Please input what you want to reverse: ")
    my_output = my_input.split()
    new_list = []
    for word in my_output:
        new_list.append(word[::-1])
    reversy = " ".join(new_list)
    print(reversy)

rev()
Output:

Output:
C:\Python36\python.exe C:/Python/Gui/tkinter/raspi/scratch1.py Please input what you want to reverse: Python forum nohtyP murof Process finished with exit code 0
In [1]: output = ' '.join([word[::-1] for word in 'Python forum'.split()])

In [2]: output
Out[2]: 'nohtyP murof'