Python Coding - How to reverse an input string ?
- shivam07das
- Dec 29, 2022
- 2 min read
Updated: Jan 2, 2023
Given an input string S, we want to print the reverse of that string. Python already has an in-built reverse() function but we don't want to use that. Instead we will write a program to implement the same functionality.

Shown below is the Python code that will accept a string and print the reverse of it
1. s: str = input()
2. sl = list(s)
3. i = 0
4. n = len(sl) - 1
5. while i <= n:
6. m = sl[i]
7. sl[i] = sl[n]
8. sl[n] = m
9. i = i + 1
10. n = n - 1
11. os = "".join(sl)
12. print(os)The main idea behind the algorithm is as follows:
Using two pointer variables, we start moving from the 'left' (start) and from the ' right (end) of the input string at the same time. As we move towards the center, at each position, we swap the left and right content. We keep doing this when we have reached the middle. Finally we create a new string by joining all the characters of the swapped list and print
Let's now analyze the key sections of the code
Line 1 - 4 : The input in provided by the user and stored in variable `s`. In line 2, we use the `list()` function to split the input into the individual characters e.g. if s = "apple", the `sl = ["a", "p", "p", "l", "e"]`. Line 3 we initialize the variable `i = 0 and set `n` to the size of the input. These are the two key variables we will use
Line 5 : while (i <= n) starts the loop to go through all the `n` characters in the input string. The control will exit from the loop when value of variable "i" will become greater than value of 'm'
Line 6 - 8: We use another variable `m` to swap the characters at position [i] and [m]
Line 9-10: We increment the variable 'i' by 1 i.e. we move 1 position to the right. and decrement the variable 'm' by 1 i.e. we move 1 position to left
Line 11: Now that the entries in the input list 'sl' has been swapped, we use the "join()" function to concatenate the characters to form the reversed string and store it in a new variable 'os'
Line 12: Print the variable 'os' which now holds the "reverse" of the input string
And that's it ! We have written a program to print the reverse of an input string



Comments