Python_Slicing_Tutorial
Python_Slicing_Tutorial
Slicing is a technique in Python that allows us to extract a specific part of a sequence (like a string,
list, or tuple). It follows this syntax:
sequence[start:stop:step]
We can reverse a string in Python using slicing by setting the step value as -1.
word = "Python"
print(reversed_word)
Output:
nohtyP
Output:
Hello
word = "ABCDEFGHIJ"
Output:
ACEGI
text = "PythonProgramming"
Output:
gnimmargorP
numbers = [1, 2, 3, 4, 5]
Output:
[5, 4, 3, 2, 1]
In Python, when reversing a string using slicing, we usually set the step as -1 ([::-1]). However, we
can also control the reversal by using the stop index.
text = "Python"
Python Slicing & Reversing a String
reversed_part = text[:3:-1]
print(reversed_part)
Output:
noh
text = "PythonProgramming"
print(extracted_part)
Output:
Programming
print(reversed_part)
Output:
gnimmargorP