How to Select Specific Ranges from a String
Slicing is a technique used to create a new data structure by selecting a contiguous segment of elements from an existing data structure (like lists or strings).
The slicing operator [:]
is used to select or extract specific parts of a string. Through slicing, you can easily obtain particular ranges from a string.
How to Use
The slicing operator uses square brackets with a start index and an end index separated by a colon (':')
. The start index is inclusive, while the end index is exclusive.
Let's look at the example below.
String Slicing Example
text = "The waves of the sea gently come at night"
slice_text_1 = text[0:3] # "The": from the 0th index 'T' to just before the 3rd index ' '(space)
slice_text_2 = text[17:20] # "the": from the 17th index 'o' to just before the 20th index 'a'
print("slice_text_1:", slice_text_1)
print("slice_text_2:", slice_text_2)
Various Slicing Techniques
-
Omitting the Start Index
: Slice from the beginning of the string. -
Omitting the End Index
: Slice from the specified start index to the end of the string.
String Slicing Example
text = "The waves of the sea gently come at night"
first_part = text[:3] # "The"
last_part = text[25:] # "gently come at night"
reverse_slice = text[::-1] # "thgin ta emoc yltneg aes eht fo sevaw ehT"
print("first_part:", first_part)
print("last_part:", last_part)
print("reverse_slice:", reverse_slice)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.