Exercise 25

Write a Python algorithm that asks the user to enter a word and return the opposite. Example: if the user enters the word 'python', the program returns 'nohtyp'.


word = input("Enter a word: ")   # ask the user to enter a word
opposite = word[::-1]           # reverse the word using slicing
print("The opposite of", word, "is", opposite)   # print the opposite word
Enter a word: python
The opposite of python is nohtyp


  1. input("Enter a word: "): asks the user to enter a word and stores it in the word variable.
  2. word[: -1]: uses slicing to reverse the word. The [::-1] slice notation means to slice the entire string (:), with a step of -1, which reverses the order of the characters.
  3. print("The opposite of", word, "is", opposite): prints the original word and its opposite.

Other method without slicing the word:

# Ask user to enter a string s
s = input("Enter a string s : ")
# initialize the reverse of the string s to empty string
rev = ""

# Building the string s in a reversed way
for x in s:
    rev = x + rev
print("The reverse of the string : '",s,"' is : ", rev)


Younes Derfoufi

One thought on “Solution Exercise 25: python algorithm to reverse a given string”

Leave a Reply