This article will introduce a method to get a substring of a string using Python code, that is, the string slicing method.
Use the string slicing method to get the substring of a string in Python
Python doesn’t have any special function to get a substring of a string. However, we can use the string slicing method to achieve this. We treat a string as an array of characters in Python. Using this concept, we can slice out our required substring from an existing string. The correct syntax to use this method is as follows:
The detail of this method is as follows:
||optional||It is the starting point of our substring. If omitted, then the substring starts from the start of the given string.|
||optional||It is the ending point of our substring. If omitted, then the substring ends where our string ends.|
||optional||It tells about the skipping of any character. If it is 2, then after one character, one character will be skipped.|
The program below shows how we can use this method to get a substring of a string in Python.
string = "This is my string" print(string[5:11])
We have sliced out characters from index 5 to 11.
Let’s see the result if we pass nothing.
string = "This is my string" print(string[::])
This is my string
Now, if we also pass the stepping element, then the output will be as follows:
string = "This is my string" print(string[5:11:2])
From index 5 to 11, after one character, one character is skipped.