+ 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
8 Answers
+ 9
Clyde Jhan Paglinawan
x = "Hello"
y = x.lower()[::-1]
z = y.capitalize()
print(z)
+ 9
Ok Niels F đ©đȘ <html challenger> even shorter
print("Hello"[::-1].capitalize())
+ 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())
+ 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/
+ 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)
+ 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.
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)
0
After about us, contact us . What is next