Reverse string without using function in Python
In this tutorial, we will learn how to reverse a given string in Python. There are many methods but let’s see how to do it without using functions.
I hope you know how for loop works. If you don’t, then click here.
Reverse a string using for loop in Python
First of all, let’s take a string and store it in a variable my_string.
Here we have taken a string “Nitesh Jhawar” which is stored in my_string.
Since we are not using any function, we will need an empty string so that we can concatenate it with each letter of the string using a for loop which we will be discussing in the next step.
Now because we are using a for loop, therefore let us see its syntax:
for iterating_variable in string_name
for i in my_string:
Now, since we are iterating, we will be using the iterating variable.
We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time.
By end of the for loop, str will contain the given string in reverse order.
Finally, Our code looks like,
my_string=("Nitesh Jhawar") str="" for i in my_string: str=i+str print("Reversed string:",str)
Reversed string: rawahJ hsetiN