Python String: Slicing

1. Introduction to the String Slicing Operator

In Python, the colon (:) acts as the string slicing operator. It’s used to extract a specific portion (substring) of a string using index positions. This technique helps isolate certain characters without modifying the original string.
The slicing syntax follows this structure:


variable[start:end]

Explanation

  • start → The index where slicing begins (inclusive).
  • end → The index where slicing stops (exclusive, i.e., character at position end – 1 is the last included).
  • So, var[x:y] extracts characters starting at index x up to (but not including) index y.

Example 1: Using Positive Indices

When both indices are positive, Python counts from the beginning (index 0).


text = "WELCOME HOME" print("text:", text) print("text[3:8]:", text[3:8]) #Output text: WELCOME HOME text[3:8]: COME

Explanation

This extracts characters from index 3 to index 7 (excluding index 8). The substring “COME” is returned.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top