We will develop a program to reverse a string in python without using function. We are using loop and slicing operators to reverse a string in python. 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 a String Without using Function in Python
We will take a string while declaring the variables. The for loop iterates every element of the given string, joining each character in the beginning so as to obtain the reversed string. Finally, the result will be displayed on the screen.
# Python program to reverse a string using for loop
# take inputs
string = 'Know Program'
# calculate 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
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: ')
# calculate 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: For Loop
The reverse string is pooL roF
Output for the input values test-case-2:-
Enter the string: reverse
The reverse string is esrever
Reverse a String in Python Without using Function
We will also reverse a string in python using while loop. We initialized a while loop with a value of the string.
# 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: python
The reverse string is nohtyp
Python Program to Reverse a String Without using Function
The slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end.
# Python program to reverse a string using slicing
# take inputs
string = input('Enter the string: ')
# find reverse of string
reverse = string[::-1]
# print reverse of string
print('The reverse string is', reverse)
Output:-
Enter the string: slicing
The reverse string is gnicils