Python Slicing Strings
2 min read ·
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:
start→ index to begin slicing (included)end→ index to stop slicing (excluded)
Basic String Slicing
Slice from Start
If you omit the start index, Python starts from index
0.Slice Till End
If you omit the end index, Python slices till the end of the string.
Negative Index Slicing
Python allows negative indexing, which starts counting from the end.
Slice with Step
You can control the step size (how many characters to skip).
Syntax
Reverse a String Using Slicing
Slicing can be used to reverse a string easily.
Slicing with Variables
Common Slicing Mistakes
Out-of-range Index (No Error)
Empty Slice
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
Exercise
- Slice first 4 characters of a string
- Slice last 3 characters using negative indexing
- Reverse your name using slicing