How to reverse a word? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
+ 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
8 Réponses
+ 9
Clyde Jhan Paglinawan x = "Hello" y = x.lower()[::-1] z = y.capitalize() print(z)
25th May 2024, 4:41 PM
BroFar
+ 9
Ok Niels F 🇩🇪 <html challenger> even shorter print("Hello"[::-1].capitalize())
25th May 2024, 5:17 PM
BroFar
+ 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
+ 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
+ 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>
+ 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
0