How to extract a substring in Python

Python allows the user to extract a substring out of a stringalso known as splicing with the : operator.

Syntax

The syntax to slice a string is as follows.


string[start: end: step]

Parameters

  • start indicates the starting index from where the string needs to be spliced.

  • end specifies the index of the string until which splicing needs to be done.

  • step specifies the number of steps needed to jump from the current index to the next index of the string.

If step is not specified, it stays at 1.

Code

The string is initially spliced in the code below by specifying the starting and ending index.

With the step value set to 2, the string is extracted by skipping every character after the starting index.

If the starting index is not given, the splicing has to start from index 0.

Similarly, if the ending index is not given, the splicing needs to be done until the end of the string.

# splicing without specifying any step
string = "Educative"
x = string[2:4]
print (x)
# splicing with a specified step
y = string[0:7:2]
print (y)
# splicing without specifying the starting index
z = string[:3]
print (z)
# splicing without specifying the ending index
a = string[3:]
print (a)