Last Updated on May 4, 2024 by Roshan Parihar
To get a substring from a string from the required position in Python, use the slice(:
) operator.
You can also use the double slice (::
) operator to find the substring from the specified position of the string in Python. Let’s find out with the example given below here.
How to Get Substring From String Using slice(:) in Python?
If you want to get the 2 substrings from the start and end position of the string, you have to use the single slice (:
) operator followed by the number of substrings.
Example 1
1 2 3 4 5 6 7 8 9 10 11 |
#Define string in Python myStr = "TutorialDeep!" #Get 2 substrings from start and end using slice(:) strStart = myStr[:2] strEnd = myStr[-2:] #Print result print("Initial string is: ", myStr) print("Two substrings from start: ", strStart) print("Two substrings from the end: ", strEnd) |
Output
Two substrings from the start: Tu
Two substrings from the end: p!
The output in the above example shows the two substrings collected from the start and end positions of the string. Similarly, you can obtain more items by increasing the number with the slicing operator in the above example.
Using Double slice(::) to Find Substring From String in Python
You can find the substring from a certain positional gap in a string using Python. To get the substring with certain gapping in the positions, you have to use the double slice (::
) operator followed by the number of gapings.
Suppose, if you want to collect substrings with positional gapping of 2, you have to use the double slicing (::
) operator followed by 2. See the example given below to learn the required method.
Example 2
1 2 3 4 5 6 7 8 9 |
#Define string in Python myStr = "T-u-t-o-r-i-a-l-D-e-e-p-!" #Get 2 substrings after a certain positional gap using double slice(::) strPosGap = myStr[::2] #Print result print("Initial string is: ", myStr) print("Substring after a positional gap of 2: ", strPosGap) |
Output
Substring after positional gap of 2: TutorialDeep!
As a result, you will get the substring in the above example after collecting from the string with a positional gapping of 2.
Get Substring From Specified Position of String in Python
In addition to the above methods, you can also get the substring from the specified position in Python. To collect substring from the required position, you have to use the positional number followed by the slicing (:
) operator. Let’s collect the substring from the 2nd position of the string in the below example.
Example 3
1 2 3 4 5 6 7 8 9 |
#Define string in Python myStr = "TutorialDeep!" #Get substring from the specified position using slice(:) strSpecified = myStr[2:] #Print result print("Initial string is: ", myStr) print("Substring after 2nd position: ", strSpecified) |
Output
Substring after 2nd position: torialDeep!
The above example collected all the string characters from the 2nd position specified with the slicing operator.
You May Also Like to Read