How to Get Substring From a String in Python

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

Output

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

Output

The 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 the substring from the 2nd position of the string in the below example.

Example 3

Output

The 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.