python substring

How to work with python substring in 2022

Python provides many ways to get the string out of a substring, which we usually call slicing. In this blog, we will learn all about python substring. so let’s get started.

Various methods to create a substring in python

python substring

There are numerous ways in which a user can create a substring in python. In this session, we will go through each of the processes.

Python Substring using slicing

The first method to extract a substring is using the slicing method. The slicing method slices the string based on the index of the character. Let’s create a simple string that we will be using for demonstration.

a = "hello from naiveskill"

Now extract the naiveskill from string a.

a[11:21]
Python Substring using slicing

Python substring regex

The second method to extract a substring is using regex. using the regex method a user can perform complex searches. Let’s use the regex to extract naiveskill from “hello from naiveskill”

import re
a = "hello from naiveskill"
result = re.search('naiveskill',a)
result.group()
Python substring regex

Python substring before a character

In this session, we will understand how to get a substring that occurs before a character. Suppose the string is “Hello: how are you” and we wish to get the Hello from the string. This can be achieved using the below code.

c = "Hello: how are you"
split = c.split(":")
split[0]
Python substring before a character

Python substring after a character

In the same way, if the user wishes to get are from “Hello: how are you”, he/she can use the below code snipped.

c = "Hello: how are you"
split = c.split(" ")
split[2]
Python substring after a character

Python substring index

So far we have understood how to get the substring from a string. In this session, we will understand how to get the index of a substring inside the string. To get the index we have to use the python index() method. The index method follows the below pattern.

str.index(sub[, start[, end]] )

where

  • sub – substring to be searched in the string str
  • start and end(optional) – substring to be searched in that range str[start: end]

Let’s use the index method to get the index of how in “Hello: how are you”.

c = "Hello: how are you"
c.index("are")
Python substring index

Conclusion

I hope you have liked this small tutorial on python substring. please reach out to me in case you are facing any issues while following along.

More to read

Python requests post and get

Jenkins job to create a python virtual environment

Leave a Comment

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

Scroll to Top