Python Substring Method – Definitive Guide

Python Strings are a sequence of characters enclosed with single quotes or double quotes.

Getting a substring of a string is extracting a part of a string from a string object. It is also called a Slicing operation.

You can get a substring from a string using the str[0:n] option in python.

If You’re in Hurry…

You can use the below code snippet to get a substring of a string.

Snippet

str = "stackvidhya"

print(str[0:5])

Where,

  • str[0:5]0 means the starting position of the substring to be extracted. 5 means the ending position of the substring to be extracted.

You’ll see the first five characters extracted as substring from the main string as shown below.

Output

    stack

This is how you can get a substring from a string using the slice notation.

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to get a substring of string and how it can be used in different scenarios.

If you just want to check if a substring is available in String, read how to check if a string contains substring?

Python Substring Using slicing notation

In python, you can use the slice notation to get the substring from String.

The slicing notation accepts three optional parameters as shown below.

string[start: end: step]

Where,

  • string – The string object from which the substring should be extracted
  • start – Starting position from which the substring should be extracted. Start position is inclusive.
  • end – Ending position until which the substring should be extracted. End position is exclusive.
  • step – Number of characters to step after including each character. By default, its 1.

The below example shows how to get the substring of the first five characters from a string.

Example

string = "stackvidhya"

print(string[0:5])

You’ll see the first five characters extracted as substrings.

Output

    stack

Python Substring Using Index

In this section, you’ll learn how to extract a substring using the index positions.

Use the below example to fetch the substring from the index position 5 to 11.

Snippet

string = "stackvidhya"

print(string[5:11])

Where,

  • string – Name of the string from which the substring should be extracted
  • 5 -Starting index of the substring. Inclusive
  • 11 – Ending index of the substring. Exclusive

You’ll see the substring extracted from position 5 to 10 as shown below.

Output

    stack

Using Step Optional Parameter

You can use the step parameter to ignore some characters while getting substrings from a string.

For example, if you use 2 as a step parameter, 1 character will be ignored after including each parameter in the substring. This ideally means, 2 steps will be moved after including a character.

Snippet

string = "stackvidhya"

print(string[0:5:2])

Where,

  • 0 – Start Position of the substring, inclusive
  • 5 – End position of the substring, Exclusive
  • 2 -Number of steps to be moved after including a character. If you use 2, one character will be ignored after including each character.

After including s, two steps are moved and t is ignored. Then a is included. Then two steps are moved and c is ignored and k is included.

Output

    sak

This is how you can extract a substring from a string using the index position and the step parameters.

Python Substring Before Character

You can extract a substring from a string before a specific character using the rpartition() method.

rpartition() method partitions the given string based on the last occurrence of the delimiter and it generates tuples that contain three elements where.

  • First element would be String until the last occurrence of the delimiter.
  • Second element would be the delimiter string itself.
  • Third element would be the String after the last occurence of the delimiter.

There is also a method known as rsplit() which splits the string multiple times if the string contains the delimiter multiple times. Whereas rpartition() splits the string only once even if the delimiter exists multiple times in the string.

Use the below snippet to split the string before the character _.

Snippet

string = "stack_vidhya"

print(string.rpartition('_')[0])

Where,

  • string -Source string from which the substring should be extracted
  • rpartition('_') – To partition the string based on the delimitor _.
  • [0] – To access the first element in the tuple generated by the rpartition(). This is to extract the substring before the delimiter character.

You’ll see the output stack which is a substring until the character _.

Output

    stack

This is how you can substring before a specific character.

Python Substring After Character

You can extract a substring from a string after a specific character using the partition() method.

partition() method partitions the given string based on the first occurrence of the delimiter and it generates tuples that contain three elements where.

  • First element would be String until the first occurrence of the delimiter.
  • Second element would be the delimiter string itself.
  • Third element would be the String after the first occurence of the delimiter.

There is also a method known as split() which splits the string multiple times if the string contains the delimiter multiple times. Whereas partition() splits the string only once even if the delimiter exists multiple times in the string.

Use the below snippet to split the string after the character _.

Snippet

string = "stack_vidhya"

print(string.partition("_")[2])

Where,

  • string -Source string from which the substring should be extracted
  • partition('_') – To partition the string based on the delimitor _.
  • [2] – To access the last element in the tuple generated by the partition(). This is to extract the substring after the delimiter character.

You’ll see the output stack which is a substring after the character _.

Output

    vidhya

This is how you can extract substring after a specific character.

Python Substring Until Character

You can extract a substring from a string until a specific character using the partition() method.

partition() method partitions the given string based on the first occurrence of the delimiter and it generates tuples that contain three elements where,

  • First element would be string until the first occurrence of the delimiter.
  • Second element would be the delimiter string itself.
  • Third element would be the String after the first occurence of the delimiter.

There is also a method known as split() which splits the string multiple times if the string contains the delimiter multiple times. Whereas partition() splits the string only once even if the delimiter exists multiple times in the string.

Use the below snippet to split the string until the character _.

Snippet

string = "stack_vidhya"

print(string.partition("_")[0])

Where,

  • string -Source string from which the substring should be extracted
  • partition('_') – To partition the string based on the delimitor _.
  • [0] – To access the first element in the tuple generated by the partition(). This is to extract the substring until the delimiter character.

You’ll see the output stack which is a substring until the character _.

Output

    stack

This is how you can extract a substring until a specific character.

Get First Character of String

You can get the first character of a string by using the index 0.

Snippet

string = "stackvidhya"

print(string[0])

Where,

  • string – Source string to extract the substring
  • [0] – To get the first character of the String

Output

    s

This is how you can get the first character of the string.

Get Last Character of String

You can get the first character of a string by using the index -1. - sign indicates that the string should be traversed from the end.

Snippet

string = "stackvidhya"

print(string[-1])

Where,

  • string – Source string to extract the substring
  • [-1] – To get the last character of the String

Output

    a

This is how you can generate the last character of the string.

Python Substring Using Regex

You can get a substring of a string using the Regular expressions when you do not know the conditions beforehand.

First, import the package re using the import re statement.

Then you can use the re.split() method to get the substring based on the regular expression.

The split method accepts two parameters where,

  • an Expression – a regular expression to match
  • String – Source string to match the expression

And it returns a list of the split string.

To learn more about the regular expression, refer regular expression cheat sheet.

Now use the below snippet to split the string based on the delimiter ‘_`.

Snippet

import re

string = "stack_vidhya"

result = re.split("_+", string)

print(result)

You’ll see the below output list which contains the spit strings based on the delimiter.

If you want to get only one element from the list, then you can use the list index to access the elements.

Output

    ['stack', 'vidhya']

This is how you can extract the substring using regular expressions also known as pattern matching.

Conclusion

To summarize, you’ve learned how to get a substring from a string in python using the slicing notation. Also, you’ve learned how to use the slicing notation to get the substring in various scenarios and how to extract the substring using regular expressions and pattern matching.

If you have any questions, comment below.

You May Also Like

Leave a Comment