How to do Cutting and Slicing Strings in Python

Basic String Slicing Syntax

Use the slicing syntax string[start:end] to extract a portion of a string. For example, text[0:5] will give the first 5 characters.

Omitting Start or End

If you omit the start index, Python will start slicing from the beginning. For example, text[:5] gives the first 5 characters. Omitting the end index like text[5:] returns everything from the 5th character onwards.

Using Negative Indexing

Python allows negative indexing to slice from the end of the string. For example, text[-5:] gives the last 5 characters of the string.

Step Parameter in Slicing

The slicing syntax can include a third parameter for steps: string[start:end:step]. For example, text[::2] will return every second character of the string.

Reversing a String with Slicing

You can easily reverse a string by using a negative step value. For example, text[::-1] returns the string in reverse order.

Slicing with Variables

Instead of hardcoded numbers, you can use variables to define the start, end, and step. For instance, text[start:end:step] lets you dynamically slice based on variable values.

Handling Out-of-Bounds Indexes

If your slicing exceeds the string's length, Python will not throw an error. For example, text[:100] will simply return the entire string if it’s shorter than 100 characters.

Learn More String Operations at PythonCentral.io

Want to dive deeper into Python string manipulation? Visit PythonCentral.io for comprehensive tutorials and advanced techniques!