How to reverse a word? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 - avatar
+ 9
Ok Niels F 🇩🇪 <html challenger> even shorter print("Hello"[::-1].capitalize())
25th May 2024, 5:17 PM
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 - 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:
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 - avatar
The following link takes you to Online Python Compiler, where it loads the code answered by @BroFar, and runs the program.
26th May 2024, 12:01 PM
Mallikarjun M
Mallikarjun M - avatar
After about us, contact us . What is next
27th May 2024, 10:59 AM
Bello Rukayat
Bello Rukayat - avatar