+ 3

How to reverse a word?

In python, how do I code to reverse words? Example : Hello, Olleh. I'm really curious and thank you for answering

25th May 2024, 4:36 PM
Clyde Jhan Paglinawan
Clyde Jhan Paglinawan - avatar
8 Answers
+ 9
Clyde Jhan Paglinawan x = "Hello" y = x.lower()[::-1] z = y.capitalize() print(z)
25th May 2024, 4:41 PM
BroFar
BroFar - avatar
+ 9
Ok Niels F đŸ‡©đŸ‡Ș <html challenger> even shorter print("Hello"[::-1].capitalize())
25th May 2024, 5:17 PM
BroFar
BroFar - avatar
+ 8
we should not hunt for the shortest code. the zen of python says: **readability counts**. this sample is not the shortest code, but for the sake of *understanding* and *readability* it may help beginners. we are iterating on the input string character by character and build a new string. after iteration is done, we capitalize the new reversed word and print it. word = 'Hello' new_word = '' for char in word: new_word = char + new_word print(new_word.capitalize())
25th May 2024, 5:38 PM
Lothar
Lothar - avatar
+ 7
No one has said what ::-1 means. The examples above are using slice notation The syntax: sequence[start:stop:step] word = "Hello" reverse = word[::-1] print(reverse) [::-1] extracts the characters of the string in reverse order Learn more here: https://sentry.io/answers/JUMP_LINK__&&__python__&&__JUMP_LINK-slice-notation/
25th May 2024, 8:29 PM
Chris Coder
Chris Coder - avatar
+ 6
BroFar Your code works but the lower method is not necessary because the capitalize method returns a new string with the first letter capitalized and the rest of the letters in lowercase. So this is enough: x = "Hello" y = x[::-1] # reverses the string z = y.capitalize() #capitalizes the first letter and lowers the rest print(z) or short x = "Hello" y = x[::-1].capitalize() print(y)
25th May 2024, 5:01 PM
Niels F đŸ‡©đŸ‡Ș <html challenger>
Niels F đŸ‡©đŸ‡Ș <html challenger> - avatar
+ 2
Should probably do what Lothar says but if you really want the shortest code then I recommend atleast putting a comment explaining what x[::-1].capitalize() is doing.
25th May 2024, 8:08 PM
Junior
Junior - avatar
0
The following link takes you to Online Python Compiler, where it loads the code answered by @BroFar, and runs the program. https://programguru.org/online-compiler/python?heading=Reverse%20and%20Capitalize%20the%20String&program=x%20%3D%20%22Hello%22%0Ay%20%3D%20x.lower()%5B%3A%3A-1%5D%0Az%20%3D%20y.capitalize()%0Aprint(z)
26th May 2024, 12:01 PM
Mallikarjun M
Mallikarjun M - avatar
0
After about us, contact us . What is next
27th May 2024, 10:59 AM
Bello Rukayat
Bello Rukayat - avatar