Python program to reverse a string

In this program we shall learn how to invert a string. For example if there is a string ‘hello’. The result should be ‘olleh’.

To understand this example you should have knowledge of following topics in python –

  • Strings
  • Loops
  • Looping through a string

Program

word = "apple"
print("Given word is ", word)
length = len(apple)
i = length - 1
empstr = ""
while i >= 0:
    empstr += word[i]
    i+=1
print("The output is ", empstr)

Output

Given word is apple

The output is elppa

Taking string from a user

word = input("Enter a string: ")
length = len(word)
i = length - 1
empstr = ""
while i >= 0:
    empstr += word[i]
    i-=1
print("The output is ", empstr)

Output

Enter a string: peacock

The output is kcocaep

Explanation

  • First of all we have taken a string and stored it inside  variable named ‘word’.
  • Then we have calculated the length (number of characters) of the string using the inbuilt function ‘len()’ and stored it in a variable named ‘length’.
  • We need to execute a loop starting from the last index of the string. The last index of the string would be 1 less than its actual length. For example if the string is ‘cycle’, its length is 5, so its last index would be 4. In order to get the characters from the last end we need to execute a reverse loop from last index to 0.
  • We have declared a variable named ’empstr’ and have stored an empty string inside it. We would then append the individual characters one by one from the end of the string to this empty string.
  • Lastly, we have executed a while loop from the last index to 0, and inside this loop we are appending the particular character to the empty string. Once the loop completes, the result would be stored in ’empstr’.

Making this example by for loop

word = input("Enter a string")
length = len(word)
i = length - 1
for x in range(i, -1, -1):
    empstr += word[x]
print("The result is ", empstr)

Note :- Running a for loop in backward direction needs the third parameter to be passed in the range function. This parameter should not be ignored even if there is no gap between the intervals and it should be -1 in the case of consecutive descending numbers.