Basic Slicing
The basic syntax for slicing in Python is:
string[start:stop:step]
- start: The index where slicing starts (inclusive). If omitted, slicing starts from the beginning of the string.
- stop: The index where slicing ends (exclusive). If omitted, slicing goes to the end of the string.
- step: The step size or increment between indices. If omitted, the step is 1 (i.e., every character).
Examples of Basic Slicing
Simple Substring Extraction:
string = "Python Programming" substring = string[7:18] # Extracts from index 7 to 17 print(substring) # Output: "Programming"
Here, start is 7 and stop is 18. It extracts characters from index 7 to 17 (index 18 is not included).
Slicing with a step of 2:
string = "Python Programming" substring = string[0:18:2] # Extracts from index 0 to 17, stepping by 2 print(substring) # Output: "Pto rgamn"
Here, step is 2. It extracts every second character from the string.
Slicing with a Negative step:
string = "Python Programming" substring = string[18:7:-1] # Extracts from index 18 to 8 in reverse order print(substring) # Output: "gnimmargorP"
Here, step is -1, which means extracting characters in reverse order. start is 18 and stop is 7 (not included).
Omitting Indices:
string = "Python Programming" # Extraction from the beginning to index 10 print(string[:10]) # Output: "Python Pro" # Extraction from index 7 to the end print(string[7:]) # Output: "Programming" # Extraction of the entire string with a step of 3 print(string[::3]) # Output: "Ph rgmi" # Reversing the entire string print(string[::-1]) # Output: "gnimmargorP nohtyP"
- Omitting start implies starting from the beginning of the string.
- Omitting stop implies slicing until the end of the string.
- Omitting both parameters returns a full copy of the string.
- Using a negative step reverses the string.
Important Points to Note
- Valid Indices: Indices must be integers. You can use integer variables or expressions that evaluate to integers.
- Out-of-Bounds Indices: If start is greater than the length of the string, the result will be an empty string. Similarly, if stop is less than start, the result will also be an empty string.
string = "Python" print(string[10:]) # Output: "" print(string[4:2]) # Output: ""
- Negative step Behavior: When using a negative step, start must be greater than stop. Otherwise, the result will be an empty string.
string = "Python" print(string[5:1:-1]) # Output: "hty"
Post Views: 563