Lecture
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)
Previous lessonSelecting Specific Parts of a String Using IndexingNext lessonHandling Exceptions with try and except
Lessons in this chapter · Data Types in Pythons
- 1. Data Types Representing Kinds of Data
- 2. How to Represent Text, Numbers, and True/False in Python
- 3. How to Check Variable and Value Types
- 4. What to Watch Out for When Creating String Data?
- 5. Understanding and Using Escape Characters
- 6. How to Create Multiline Strings?
- 7. Multiple-choice quiz
- 8. Concatenating Strings with the `+` Operator
- 9. Using the (*) Operator for String Repetition
- 10. Selecting Specific Parts of a String Using Indexing
- 11. How to Select Specific Ranges from a String
- 12. Handling Exceptions with try and except
- 13. String IndexError(index out of range) Exception
- 14. Python String Indexing Coding Quiz
- 15. Multiple-choice quiz
- 16. Fill-in-the-blank quiz
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help