String slices
Python slicing is a sub-string of the given string from start to end.
The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__()
and __len__()
method).
slice() Constructor
The syntax of slice()
:
- slice(stop)
· slice(start, stop, step)
slice() Parameters
Three parameters:
- Start (optional) - where the slicing of the object starts. Default to none if not provided.
- Stop – Integer value until the slicing takes place. The slicing stops at index stop -1 (last element).
- Step (optional) - Integer value which determines the increment between each index for slicing. Defaults to none if not provided.
Return Type: Returns a sliced object containing elements in the given range only.
Index tracker for positive and negative index:
Negative comes into considers when tracking the string in reverse.
![](https://www.drpankajdadhich.com/wp-content/uploads/2020/12/image-21.png)
The operator [n : m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. It help to the indices pointing between the characters.
If omit the first index (before the colon), the slice starts at the beginning of the string and If omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
If the first index is greater than or equal to the second the result is an empty string, represented
by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
' ' An empty string contains no characters and has length 0, but other than that, it is the same
as any other string.
String ='ASTRING' # Using slice constructor s1 = slice(3) s2 = slice(1, 5, 2) s3 = slice(-1, -12, -2) print("String slicing") print(String[s1]) print(String[s2]) print(String[s3]) |
Output:
String slicing
AST
SR
GITA
Example
String ='ASTRING' # Prints string in reverse print("\nReverse String") print(String[::-1]) |
Output:
Reverse String
GNIRTSA
s = 'HelloWorld'
reverse_str = s[::-1]
print(reverse_str)
Output: dlroWolleH
Examples:- Steps and negative index values.
s1 = s[2:8:2]
print(s1)
Output: loo
Here the substring contains characters from indexes 2,4 and 6.
s1 = s[8:1:-1]
print(s1)
Output: lroWoll
Here the index values are taken from end to start. The substring is made from indexes 1 to 7 from end to start.
s1 = s[8:1:-2]
print(s1)
Output: lool
Python slice works with negative indexes too, in that case, the start_pos is excluded and end_pos is included in the substring.
s1 = s[-4:-2]
print(s1)
Output: or
Example 1: Create a slice object for slicing
# contains indices (0, 1, 2)
result1 = slice(
3)
print(result1)
# contains indices (1, 3)
result2 = slice(
1,
5,
2)
(slice(
1,
5,
2))
Output
slice(None, 3, None)
slice(1, 5, 2)
Example 2: Get substring using slice object
# Program to get a substring from the given string
py_string =
'Python'
# stop = 3
# contains 0, 1 and 2 indices
slice_object = slice(
3)
(py_string[slice_object])
# Pyt
# start = 1, stop = 6, step = 2
# contains 1, 3 and 5 indices
slice_object = slice(
1,
6,
2)
print(py_string[slice_object])
# yhn
Output
Pyt
yhn
Example 3: Get substring using negative index
py_string =
'Python'
# start = -1, stop = -4, step = -1
# contains indices -1, -2 and -3
slice_object = slice(
-1,
-4,
-1)
print(py_string[slice_object])
# noh
Output
noh
Example 4: Get sublist and sub-tuple
py_list = [
'P',
'y',
't',
'h',
'o',
'n']
py_tuple = (
'P',
'y',
't',
'h',
'o',
'n')
# contains indices 0, 1 and 2
slice_object = slice(
3)
(py_list[slice_object])
# ['P', 'y', 't']
# contains indices 1 and 3
slice_object = slice(
1,
5,
2)
print(py_tuple[slice_object])
# ('y', 'h')
Output
['P', 'y', 't']
('y', 'h')
Example 5: Get sublist and sub-tuple using negative index
py_list = [
'P',
'y',
't',
'h',
'o',
'n']
py_tuple = (
'P',
'y',
't',
'h',
'o',
'n')
# contains indices -1, -2 and -3
slice_object = slice(
-1,
-4,
-1)
(py_list[slice_object])
# ['n', 'o', 'h']
# contains indices -1 and -3
slice_object = slice(
-1,
-5,
-2)
print(py_tuple[slice_object])
# ('n', 'h')
Output
['n', 'o', 'h']
('n', 'h')
Example 6: Using Indexing Syntax for Slicing
For example,
py_string =
'Python'
# contains indices 0, 1 and 2
(py_string[
0:
3])
# Pyt
# contains indices 1 and 3
(py_string[
1:
5:
2])
# yh
Output
Pyt
yh
===================================================================
0 Comments