Interview question: Reverse a string in Python

Crystal X
3 min readMay 3, 2023

If a person is going on a job interview as a Python developer, he will no doubt be asked a few Python programming questions to test his knowledge. One question that may very well come up is how to reverse a string. There are several ways that this question can be answered, so I will endeavour to tackle it in this blog post.

The first way to reverse a string in Python, which is the easiest way is to use slicing, which takes the form [start:stop:step].In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, “repeatedly step from right to left by 1 character”.

The code below is a depiction of slicing to reverse a string:-

A second way to reverse a string in Python is to use recursion. Recursion is the concept of calling a defined function within the function, and in Python it is possible to do this.

In the code below:-

  1. Define the variable, s.
  2. Defined the function, reverse, that accepts the string as the input. If the length of the string is 0 then return the string. If the length of the string is not 0 then return the function of the string with position 0 removed plus position 0 of the string.

--

--

Crystal X

I have over five decades experience in the world of work, being in fast food, the military, business, non-profits, and the healthcare sector.