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:

def 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.

Solution:
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

PYTHON
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Example:
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.

Leave a Reply