We will develop a program to reverse a string in python using while loop. We initialized a while loop with a value of the 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.
Example of reverse string:-
String: Know Program
Reverse String: margorP wonK
Reverse a String using While Loop in Python
We will take a string while declaring the variables. Then, find the reverse of the string using while loop. Finally, the result will be displayed on the screen.
# Python program to reverse a string using while loop
# take inputs
string = 'Know Program'
# find reverse of string
i = string
reverse = ''
while(len(i) > 0):
if(len(i) > 0):
a = i[-1]
i = i[:-1]
reverse += a
# print reverse of string
print('The reverse string is', reverse)
Output:-
The reverse string is margorP wonK
Reverse a String in Python using While 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 while loop
# take inputs
string = input('Enter the string: ')
# find reverse of string
i = string
reverse = ''
while(len(i) > 0):
if(len(i) > 0):
a = i[-1]
i = i[:-1]
reverse += a
# print reverse of string
print('The reverse string is', reverse)
Output for the input values test-case-1:-
Enter the string: While Loop
The reverse string is pooL elihW
Output for the input values test-case-2:-
Enter the string: reverse
The reverse string is esrever
Output for the input values test-case-3:-
Enter the string: Python
The reverse string is nohtyP
String Reverse in Python using While Loop
We can also take the help of a function to reverse a string in python using while loop. A function is a block of code that performs a specific task.
# Python program to reverse a string using while loop
def findReverse(string): #user-defined function
#find reverse of string
i = string
reverse = ''
while(len(i) > 0):
if(len(i) > 0):
a = i[-1]
i = i[:-1]
reverse += a
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: String
The reverse string is gnirtS