Python Slicing Strings
String slicing in Python is used to extract a portion of a string.
It allows you to get specific characters or a range of characters from a string in a clean and simple way.
Slicing is one of the most important string operations in Python.
What Is String Slicing?
Slicing means cutting a part of a string using index positions.
Python uses the following syntax for slicing:
python
string[start : end]
start→ index to begin slicing (included)end→ index to stop slicing (excluded)
Basic String Slicing
python
text = "Python"
print(text[0:3])
python
print(text[2:5])
python
print(text[1:4])
Slice from Start
If you omit the start index, Python starts from index
0.python
text = "Python"
print(text[:4])
python
print(text[:2])
python
print(text[:5])
Slice Till End
If you omit the end index, Python slices till the end of the string.
python
text = "Python"
print(text[2:])
python
print(text[4:])
python
print(text[1:])
Negative Index Slicing
Python allows negative indexing, which starts counting from the end.
python
text = "Python"
print(text[-1])
python
print(text[-3:])
python
print(text[-5:-2])
Slice with Step
You can control the step size (how many characters to skip).
Syntax
python
string[start:end:step]
python
text = "Python"
print(text[0:6:2])
python
print(text[::2])
python
print(text[1::2])
Reverse a String Using Slicing
Slicing can be used to reverse a string easily.
python
text = "Python"
print(text[::-1])
python
name = "CodeMarathi"
print(name[::-1])
python
print("Hello"[::-1])
Slicing with Variables
python
text = "PythonProgramming"
start = 6
end = 17
print(text[start:end])
python
text = "LearningPython"
print(text[8:14])
python
text = "AmazonWebServices"
print(text[6:9])
Common Slicing Mistakes
Out-of-range Index (No Error)
python
text = "Python"
print(text[0:50])
Empty Slice
python
text = "Python"
print(text[4:2])
Important
Python slicing never throws an error for out-of-range indexes.
Why String Slicing Is Useful
String slicing helps to:
- Extract usernames, domains, IDs
- Process input data
- Clean and format text
- Perform validations
python
email = "user@gmail.com"
print(email[:4])
python
print(email[-10:])
python
print(email[5:10])
Summary
- String slicing extracts parts of a string
- Indexing starts from
0 - End index is always excluded
- Negative indexes work from the end
- Step value controls skipping
[::-1]reverses a string
Exercise
- Slice first 4 characters of a string
- Slice last 3 characters using negative indexing
- Reverse your name using slicing