CodeGym /Courses /Python SELF EN /Getting Substrings

Getting Substrings

Python SELF EN
Level 10 , Lesson 3
Available

11.1 Indexing Basics

In Python, extracting substrings is a frequently used operation, allowing you to manipulate text data and extract meaningful pieces of information from strings. Let's check out several ways to get substrings, each with its own features and use cases.

Using Slices

Slices (slices) are the primary way to grab substrings in Python. A slice is made using the syntax string[start:stop:step], where:

  • start — starting index (inclusive),
  • stop — ending index (exclusive),
  • step — step, which determines the pace of character extraction.

The slice syntax lets you specify start and end indices for the substring you want to extract.


text = "Hello, world!"
substring = text[7:12]  # Outputs 'world'
        

11.2 Incomplete Indexing

You don't have to specify all three indices for substring extraction.

  • If start is omitted, the slice begins from the start of the string.
  • If stop is omitted, the slice goes to the end of the string.
  • If step is omitted, the characters are extracted one by one.

Examples:

Let's write an example to get a substring starting from the 7th character to the end of the string.


text = "Hello, world!"
substring = text[7:]  # Outputs 'world!' 

Now from the start of the string to the 10th character. Hope you remember the last character of the range isn't included in the resulting substring.


text = "Hello, world!"
substring = text[:10]  # Outputs 'Hello, wor'
        

11.3 Negative Indices

Negative indices in Python let you access string elements starting from the end. Using negative indices often makes the code more readable and convenient, especially when working with the end of a string.

Getting the last character of the string:


text = "Python"
last_char = text[-1]
print(last_char)  # Outputs: 'n'
    

Getting the second to last character of the string:


text = "Python"
second_last_char = text[-2]
print(second_last_char)  # Outputs: 'o'

Getting the last three characters of the string:


text = "Python"
last_three = text[-3:]
print(last_three)  # Outputs: 'hon'

Getting the string excluding the last character:


text = "Python"
all_but_last = text[:-1]
print(all_but_last)  # Outputs: 'Pytho'

Advanced Use of Slices

You can use the step parameter to create more complex slices, like for extracting characters in reverse order:


# Reverse the string
print(text[::-1])  # '!dlrow ,olleH'
        
2
Task
Python SELF EN, level 10, lesson 3
Locked
Substring extraction.
Substring extraction.
2
Task
Python SELF EN, level 10, lesson 3
Locked
Negative slicing
Negative slicing
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION