How to Get Substring From String in Python

Last Updated on July 12, 2021 by Roshan Parihar

In this tutorial, learn how to get substring from string using Python. The short answer is to use the slice(:) operator of Python to find the substring from the required position.

You can also use the double slice (::) operator to get 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 Start and End of String in Python

You can collect the number of substrings you want from the string in Python. Suppose you have to collect 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 to get.

Output

Initial string is: TutorialDeep!
Two substrings from start: Tu
Two substrings from the end: p!

The output in the above example shows the two substrings collected from the start and end position of the string. Similarly, you can obtain more items by increasing the number with the slicing operator in the above example.

Find Substring After Certain Positional Gap Using 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.

Output

Initial string is: TutorialDeep!
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 substring from the 2nd position of the string in the below example.

Output

Initial string is: TutorialDeep!
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

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.