Python Program To Reverse A String
Chapter:
Python
Last Updated:
17-04-2023 13:11:55 UTC
Program:
/* ............... START ............... */
string = input("Enter a string: ") # take input from user
reverse_string = string[::-1] # slice the string to reverse it
print("Reversed string:", reverse_string) # print the reversed string
/* ............... END ............... */
Output
Enter a string: Hello World
Reversed string: dlroW olleH
Notes:
-
First, we prompt the user to enter a string using the input() function and store it in the string variable.
- We then use a slice notation [::-1] to reverse the string. Slicing is a way to extract a part of a string, and the [::-1] slice notation creates a new string that starts from the end of the original string, goes all the way to the beginning, and steps backwards by 1 character at a time. This results in a reversed string.
- We store the reversed string in the reverse_string variable.
- Finally, we print the reversed string using the print() function.
- For example, if the user enters the string "Hello World", the program will create a new string that starts from the end of "Hello World", goes all the way to the beginning, and steps backwards by 1 character at a time, resulting in the reversed string "dlroW olleH". The program then prints this reversed string to the console.
Tags
Python Program To Reverse A String #How to Reverse a String in Python