String Slicing in Python 3
String slicing is a powerful feature in Python that allows us to extract a portion of a string using index ranges. It is widely used in real-world applications such as data cleaning, parsing, and text processing.
What is String Slicing?
String slicing means extracting a part of a string by specifying a start index and an end index.
Syntax:
string[start : end : step]
• end → ending index (exclusive)
• step → number of characters to skip (optional)
Basic String Slicing
Let us start with basic slicing examples.
text = "Programming"
print(text[0:6])
print(text[3:8])
Progra
gramm
Slicing with Missing Indexes
If the start or end index is not provided, Python automatically uses default values.
text = "Programming"
print(text[:5])
print(text[5:])
print(text[:])
Progr
mming
Programming
Negative Index Slicing
Python allows negative indexes to slice strings from the end.
text = "Programming"
print(text[-6:-1])
print(text[-4:])
mming
ming
Slicing with Step Value
The step value controls how many characters are skipped.
text = "Programming"
print(text[0:10:2])
print(text[::2])
Pormig
Pormig
Reverse a String using Slicing
One of the most common uses of slicing is reversing a string.
text = "Python"
print(text[::-1])
Important Rules of String Slicing
- Start index is inclusive
- End index is exclusive
- Step value cannot be zero
- Out-of-range indexes do not cause errors
Conclusion
String slicing is a simple yet powerful concept in Python. Mastering slicing helps in solving many problems efficiently and improves overall coding skills.
No comments:
Post a Comment