![]() |
Reversing word in strings yields unexpected result - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Reversing word in strings yields unexpected result (/thread-3356.html) |
Reversing word in strings yields unexpected result - Dec - May-17-2017 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. RE: Reversing word in strings yields unexpected result - metulburr - May-17-2017 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)) RE: Reversing word in strings yields unexpected result - sparkz_alot - May-17-2017 Yes, but it looks like he wants to keep the words in the same order, just reverse the letters. RE: Reversing word in strings yields unexpected result - sparkz_alot - May-17-2017 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:
RE: Reversing word in strings yields unexpected result - wavic - May-17-2017 In [1]: output = ' '.join([word[::-1] for word in 'Python forum'.split()]) In [2]: output Out[2]: 'nohtyP murof' |