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