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.
1 2 |
string = 'Hello, World!' print(string[0:5]) |
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.
1 2 |
string = 'Hello, World!' print(string.find('World', 0)) |
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
1 2 3 4 5 6 7 8 9 10 11 |
# Example code to demonstrate substring in Python # Using slicing string = 'Hello, World!' substring = string[0:5] print(substring) # Using find() string = 'Hello, World!' index = string.find('World', 0) print(index) |
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.