Reverse a String in Python using inbuilt Function

We will develop a program to reverse a string in python using inbuilt function. We are using a predefined function join(reversed()). Python reversed() method returns an iterator that accesses the given sequence in the reverse order.

Example of reverse string:-
String: Know Program
Reverse String: margorP wonK

String Reverse Function in Python

We will take a string while declaring the variables. Then, find the reverse of the string using reversed() function. Finally, the result will be displayed on the screen.

# Python program to reverse a string using inbuilt function

# take inputs
string = 'Know Program'

# find reverse using buit-in function
reverse = ''.join(reversed(string))

# print reverse of string
print('The reverse string is', reverse)

Output:-

The reverse string is margorP wonK

Reverse a String in Python using inbuilt Function

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 inbuilt function

# take inputs
string = input('Enter the string: ')

# find reverse using buit-in function
reverse = ''.join(reversed(string))

# 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-2:-

Enter the string: Python
The reverse string is nohtyP

Reverse a String using inbuilt Function in Python

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 inbuilt function

def reverse(string):   #user-defined functon
   # find reverse using buit-in functions
   reverse = ''.join(reversed(string))
   return reverse

# take inputs
string = input('Enter the string: ')

# calling function and display result
print('The reverse string is', reverse(string))

Output for the input values test-case-1:-

Enter the string: functions
The reverse string is snoitcnuf

Output for the input values test-case-2:-

Enter the string: built-in function
The reverse string is noitcnuf ni-tliub

Leave a Comment

Your email address will not be published. Required fields are marked *