Get a Substring From a String in Python

In this tutorial, we are going to learn how to get substring from a string in Python.

Strings are one of the major data types in Python. They include characters, symbols, integers or a mixture of all of the above enclosed within single or double inverted commas (‘ ‘) or (” “). Python has many built-in functions through which we can access, traverse through or modify string data types. There are many ways to get a substring from a string. This process is called slicing. It involves the use of indexing of each character in a string which starts from 0; For eg:

>>> a=”Hello”

The ‘e’ in the “Hello” holds an index of 1. Then to get the substring “ello”, see below.

a="Hello"
print(a[1:])
'ello'

Syntax: Slicing a string in Python

The syntax followed for slicing is:

>>> string[start:end:step]

Here,

  • The ‘string’ is the variable in which our main string is stored.
  • ‘start’ is the index of the character from where you want to start the substring in the main string. If not entered, it becomes the index of the first character of the main string.
  • ‘end’ is the index of the last character of the substring in the string. If not entered, it becomes the index of the last character of the main string.
  • ‘step’ is 1 by default if you don’t enter this parameter.

You may also learn: How to detect if a string contains numbers in Python?


One can not only gain access to a substring using slicing but also reverse a string.

a="Hello"
print(a[::-1])
'olleH'

The above code is used to reverse a string using slicing. The output is given in green.


To get a substring of characters from index i to j of the main string¬† stored in variable ‘str’

>>> str[i:j]

To get a substring of characters from the beginning of the main string to index j from the main string stored in variable ‘str’

>>> str[:j]

To get a substring of characters¬† from index i to the end of the main string to the end from the main string stored in variable ‘str

>>> str[i:]

To get a substring from the beginning to the end of the main string stored in variable ‘str’ discounting every 2nd character. (2 as a step)

>>> str[::2]

Now that you know the above points, let’s practice the above points.

Code: Get substring from a string in Python

a="Happy Birthday"
print(a[3:9])
print(a[:9]
print(a[5:])
print(a[::2])

Outputs:


py Bir
Happy Bir
 Birthday
HpyBrha

Code explanation:

  • The first print statement gives a substring of characters from index 3 to 9 of the main string.
  • The second print statement gives a substring of characters from the beginning of the string to index 9.
  • The third print statement gives a substring of characters from index 5 to the end of the main string.
  • The fourth print statement gives a substring of characters from beginning to the end of the main string skipping every 2nd character.

Leave a Reply

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