Python Substring | Substring of a string

A string is a sequence of characters and a substring refers to a part of a string. Python provides various methods to create a substring from a string. One most popular way is using the slicing method and another way is the split() function to create a list of substrings based on a specific delimiter. The process of getting a substring of a string is called ‘slicing’ in python.

How to create a substring using slicing?

In Python, a substring can be created using string slicing which is the most popular way of substring creation. String slicing allows you to extract a portion of a string by specifying the starting and ending indices.

Here is the syntax of creating a substring using slicing:

string[start:end:step] 

let’s break down the above syntax to understand substring in more detail.

  • In syntax “start” refers to the initial position of the substring, with the character at this index being part of the substring. If the ‘start’ value is omitted, it is considered equivalent to 0.
  • The “end:” refers to The ending index for the substring, excluding the character at this position. If ‘end’ is omitted or exceeds the string length, it defaults to the string length.
  • The Last “step:” It enables the selection of the nth item within the specified range from ‘start’ to ‘stop’.

Example

string = "Pythonsubstring"

A string’s first five characters

print(string[0:5])

//Output:Pytho

Above code print the starting alphabet characters between the given index value.

A substring of 4 characters, starting with the third character

print(string[2:6])

//Output: thon

The last character of the string

print(string[-1])

//Output: g

The last character of the string is represented by index -1, the second to last character by index -2, and so on.

The last 4 characters of a string

print(string[-4:])

//Output: ring

Substring containing all characters except the last 3 and the first

print(string[1:-4])

//Output: ythonsubst

How to Create Substrings Using Split?

Another way to create a Substring depending on the specific delimiter is by using a split method which splits the given string by spaces.

Example

sentence = "It is a part of a string that is called a substring."
print(sentence.split())

//Output: ['It', 'is', 'a', 'part', 'of', 'a', 'string', 'that', 'is', 'called', 'a', 'substring.']

How to check if a substring exist ?

The “In” operator is used to check if a substring exists in a string and will return ‘True’ if the key exists and ‘false’ if it does not exist.

Example

sentence = "It is a part of a string that is called a substring."
print("string" in sentence)

//Output: True

How to count Substring in a String?

Python string provides count method which counts the number of appearances of a character in a substring.

sentence = "It is a part of a string that is called a substring."
print(sentence.count("a"))

//Output: 6

How to find the Index of the First Substring?

The index method will give the index of the substring if it exists and if the substring does not exist it will give an error.

sentence = "It is a part of a string that is called a substring."
print(sentence.index("is"))

//Output: 3

How to find all index of the Substring?

We use the ‘for’ loop with the ‘startswith’ string method to find all the index values of the substring.

sentence = "It is a part of a string that is called a substring."
for index in range(len(sentence)):
  if sentence.startswith("a",index):
    print(index)

/*Output: 6
9
16
27
34
40*/

You can write the above code in one line using list comprehension syntax.

index_list = [index for index in range(len(sentence)) if sentence.startswith("a",index)]
print(index_list)

We have covered all the points from how to create a substring to how to work with it in Python language. All the examples given above will let you know how slicing works whether it’s extracting specific portions, finding indices, or replacing substrings and all.