Python Code To Reverse A String
Problem Statement: How to reverse a string in Python?
How Does it Work?
Following code will reverse the string using external Slicing in Python. Python slicing is computationally fast way to methodically access parts of the string.
External Slicing – Reverse String
Notation: a[starting point :ending point:step]
starting point: the beginning index of the slice. It will include the element at this index .If its negative, it means to start n items from the end.Default value is 0.
ending point: the ending index of the slice. It does not include the element at the index. Default value is length of the string.
step: the amount by which the index increases. If its negative you are slicing over the iterable in reverse. Default value is 1.
Program/Code to reverse a string:Python123456789def reverseString(str):return str[::-1]reverseString("Python is Cool!")Output:'!looC si nohtyP'# [::] is called external slicing in python. Negative value works in reversing the string.
Step 1: Input a string from the user.
Step 2: Create a function to pass string as an argument
Step 3: In the function, use External Slicing method of Python.
Step 4: Return reversed string using external slicing.
Step 5: End
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
a[::-1] —> all items in the string in reverse order. Reverse since negative value by one all the string since start and end are not specified.
a[:-3:-1] —> this will return the last two characters in reverse.
a[1::-1] —> this will return the first two character in reverse. Start with first character and reverse by one character.
Python Program – To Reverse A String – Simple Code
- Games VCF Countif Record Macro Timer in Excel Task Manager print screen HTML Table Import Data Thumbnails Text to Speech TTS Candy Crush Block Apps in FaceBook C++ Programing Machine learning AI bulk email Excel VBA vba color index vba color codes Android social media Twitter Google+ Google Adsense Tips bitcoin Calendar in Excel outlook vba mass email Data Mining Excel Macro Facebook WhatsApp python Wordpress