How to Make a Substring in Python

In Python, a substring is a string that occurs in another string. To make a substring in Python, we can simply use slicing. This approach includes specifying the start and end index, separated by a colon, to retrieve a subset of the string. In some cases, the find() function also assists.

Step 1: Python String Slicing

To use slicing, first decide the indices to slice the string.
Indexing in Python starts from 0. Negative indexes start from the end towards the beginning with -1 representing the last character in the string.

The format for slicing in Python is string[start: end: step]. The ‘start’ and ‘end’ parameters define the start and end of the slice, and ‘step’ determines the steps between each index. Not providing a ‘step’ parameter will slice the string at every index.

Step 2: Using the find() function

The find() function in Python is used to find the index of a substring within a string. It takes two parameters: the substring to find and the index to start the search from.

Step 3: Displaying Output

Now that we’ve obtained the substring, let’s print it out.

Outputs for the Above Code

Output for step 1:

Hello

Output for step 2:

7

Full Code

Conclusion

Creating a substring in Python provides a meaningful way to manipulate and handle the string data. Both slicing and the find() function can be beneficial for different scenarios and requirements.