We will develop a program to reverse a string in python using for loop. The for loop iterates every element of the given string, joining each character in the beginning so as to obtain the reversed string. The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string. The range() method returns an immutable sequence of numbers between the given start integer to the stop integer.
Example of reverse string:-
String: Know Program
Reverse String: margorP wonK
Reverse String in Python using For Loop
We will take a string while declaring the variables. Then, find the reverse of the string using for loop. Finally, the result will be displayed on the screen.
# Python program to reverse a string using for loop
# take inputs
string = 'Know Program'
# find reverse of string
reverse = ''
for i in range(len(string), 0, -1):
reverse += string[i-1]
# print reverse of string
print('The reverse string is', reverse)
Output:-
The reverse string is margorP wonK
Reverse a String in Python using For Loop
In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.
# Python program to reverse a string using for loop
# take inputs
string = input('Enter the string: ')
# find reverse of string
reverse = ''
for i in range(len(string), 0, -1):
reverse += string[i-1]
# print reverse of string
print('The reverse string is', reverse)
Output for the input values test-case-1:-
Enter the string: reverse
The reverse string is esrever
Output for the input values test-case-1:-
Enter the string: Python
The reverse string is nohtyP
Output for the input values test-case-3:-
Enter the string: programming
The reverse string is gnimmargorp
String Reverse in Python using For Loop
We can also take the help of a function to reverse a string in python using for loop. A function is a block of code that performs a specific task.
# Python program to reverse a string using for loop
def findReverse(string): #user-defined function
# find reverse of string
reverse = ''
for i in range(len(string), 0, -1):
reverse += string[i-1]
return reverse
# take inputs
string = input('Enter the string: ')
# calling function and display result
reverse = findReverse(string)
print('The reverse string is', reverse)
Output:-
Enter the string: For Loop
The reverse string is pooL roF