Python substring Explained With Examples


Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Introduction to Python substrings

In python a string is a sequence of unicode characters. It consists of a series of characters that may contain alphabets, numerics or any other special character. While python substring, as name suggests, is a sequence of characters within another string. In python we also called it the slicing of string. In this tutorial we will cover everything about python substrings. We will learn about generating substring, slicing, indexing and reversing substring. Moreover, we will also cover looping of substring using for loop.

 

Strings in Python

Strings are the most popular data type in Python. Creating strings data type is very simple in python. Everything that we will write inside double or single quotes will be considered as a Python string. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. See the example below:

# creating string
name = 'this is Bashir Alam'

# printing string
print(name)

Output:

this is Bashir Alam

A string can be one character or can contain nothing as well. See the example below:

# creating string
name = 'this is Bashir Alam'

# one character
single = "k"

# numeric string
number = "9"

# empty string
empty = ""

# printing the types of data
print(type(name))
print(type(single))
print(type(number))
print(type(empty))

Output:

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

Hence it is proved that anything that we write inside quotation marks will be treated as string data type in python.

 

String indexing in Python

In most of the programming languages, each item of an ordered set of data can be accessed directly using a numeric index or key value. This process of accessing individual items is called indexing.  In python strings are considered to be an ordered sequence of characters and thus can be indexed. Individual characters in a string can be accessed by specifying the string name followed by  a number in square brackets.

Keep in mind that string indexing starts from zero in Python. The very first character in the string has index o, the next has 1 and so on. The index of the last character will be the length of the string minus one. See the diagram below.

Python substring Explained With Examples

Now let us see and example to understand more properly, how the indexing in Python works

# creating string
name = 'this is Bashir Alam'

# printing first character
print(name[0])

# printing the 7th character
print(name[6])

Output:

t
s

Indices can be positive or negative numbers as well. The positive indices start from the beginning and go to the end of the string, and the negative indices start from the end and go to the beginning of a string.

Python substring Explained With Examples

Remember that negative indexing starts with -1 pointing to the very last element. See the example below:

# creating string
name = 'this is Bashir Alam'

# printing last character
print(name[-1])

# printing the first character
print(name[-19])

Output:

m
t

 

Python generate substring

There are different ways and methods in Python to generate a substring. First and very basic method is to extract a substring from a string by slicing with indices that get our substring. Simple syntax look like this:

String_name[start_index:stop_index:step]

Here,

  • start_index is the starting point of our substring,
  • stop_index is the position where our substring should finish. Remember that this indexed item will not be included in our substring.
  • The last is the step which is defining the steps of slicing. If we will not provide any step size, then by default the value will be one.

Now let us create a substring from the given string using the above method.

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[8:15]

# printing the substring
print(substring)

Output:

Bashir

Notice that in the above example, we didn’t explicitly define the step size so by default the value is one. Now let us define the step size to be 2.

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[0:15:2]

# printing the substring
print(substring)

Output:

ti sBsi

 

Generate Python substring using for loop

We can use for loop with a range function to return a substring. For this we have to  use the print function along with the end argument. See the example below where we define a range and generate a substring.

# creating string
name = 'This is Bashir alam'

# for loop
for i in range(2, 14):
   print(name[i], end="")

Output:

is is Bashir

 

Generate different substrings from a string

Python allows us to create substring in many different ways. One of the simplest ways is to define the starting, ending and step size, which we already had seen in the above section. In this section we will look more closely and see how to create substring in a more smarter way.

 

Example-1: Python substring containing first n characters

Creating a substring of the first n character is very simple. We can either use the above mentioned method, in which we had to define starting , ending and step size. But we can achieve the same result in a smarter way.  See the example below which prints the substring of the first 10 characters.

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[:10]

# printing the substring
print(substring)

Output:

this is Ba

Notice that we didn’t define the starting point. By default in Python, if we did not define the starting point, then it will be considered to be 0. Moreover, we also didn't defined the step size so by default it was one.

Now see the example where we explicitly mentioned the step size.

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[:10:2]

# printing the substring
print(substring)

Output:

ti sB

 

Example-2: Python substring containing last n characters

Creating substring of last n character is very much similar to creating substring of first n character with a little changes in syntax. One way is to define starting point, ending point and step size. While there is a short way to get access to the last n characters of string.

See the example below:

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[8:]

# printing the substring
print(substring)

Output:

Bashir Alam

Notice that we didn't explicitly define the stopping position. In python if we don't define the stopping position then, by default it will be the end of the string.

We can also define the step size explicitly. See the example below:

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[8::2]

# printing the substring
print(substring)

Output:

Bsi lm

 

Example-3: Python substring without starting and stopping position

We know that if we do not define the starting of indexing in the substring, then by default it will start from and beginning and if we will not define the ending of the substring then by default it will stop at the very end of the string. Now what will happen if we do not define the starting and ending of a string?

See the example below:

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[:]

# printing the substring
print(substring)

Output:

this is Bashir Alam

You can see that it prints the whole string, it is because by default the starting point is the first element and it ends when the string ends.

Now let us try to slice the string defining step size. See the example below.

# creating string
name = 'this is Bashir Alam'

# creating substring
substring = name[::2]

# printing the substring
print(substring)

Output:

ti sBsi lm

 

Check if a substring is present in a string

We can use different methods and ways to validate if a substring is inside a string or not.

 

Example-1: Check python string contains substring using in operator

Here we will discuss only two ways. See the following example, how we use the key word, in to validate if a substring is inside a string or not.

# creating string
name = 'this is Bashir Alam'

# validating substring
if "Bashir" in name:
   print("Python substring exist in main string")
else:
   print("Python substring was not found!!")

Output:

Python substring exist in main string

So the in key word here checks if the substring is in the main string, and if it finds the substring, then it returns True else it returns False. See the following example.

# creating string
name = 'this is Bashir Alam'

# checking the substring
print("Bashir" in name) #True
print("You" in name)  #false

Output:

True
False

 

Example-2: Check python string contains substring using find() function

Python is known for its various built-in functions. Python provides us with a built-in function to find a substring in a string using find() function.  Find method returns the index number, if a substring is present within another string else will return -1 if a string is not present.

See the following example:

# creating string
name = 'this is Bashir Alam'

print(name.find("Bashir"))
print(name.find("Khan"))

Output:

8
-1

You can see that the find() method returns the index number of string if it presents, else it returns -1.

Remember that python is a sensitive language. If we try to find something in upper case while it is in lower case or vice versa, python will not be able to locate it. See the example.

# creating string
name = 'this is Bashir Alam'

print(name.find("bashir"))

Output:

-1

This negative one means the given substring is not in the main string.

One more thing about find()method is that if the substring is present in more than one location, then it will only return the least indexed one and ignore the others.

See the example below:

# creating string
name = 'this is Bashir Alam. He is computer science student'
 
print(name.find("is"))

Output:

2

Notice that “is” is present in more than one location but python find() only returns the least indexed location.

 

Count occurrence of Python substring

Again there can be many ways to find out the number of occurrences of substring in a string. Python provides us with a built-in function known as count() which counts the number of occurrences of substring.

See the example below to understand count() function.

# creating string
name = 'I am Bashir Alam. I am majoring in computer science'

print(name.count("I"))
print(name.count("i"))

Output:

2
4

Notice that the count() function does not see words by words, I split the words and check each character.

We can use for loop in different ways to count the occurrence of substring. See the example below:

# creating string
name = 'I am Bashir Alam. I am majoring in computer science'

# count =0
count = 0

# using for loop to iterate
for i in name:
   if i=='I':
       # if substring is found, increase count by 1
       count+=1

print(count)

Output:

2

 

Summary

Python treats everything as string if it is written inside single or double quotes. A Python substring is a small part of a string. It can be generated in different ways. In this tutorial we covered nearly everything related to python substrings. Starting from creating substring through various ways to count the occurrence of substring in a given string, we covered all the necessary topics of substrings. Moreover, we also learned about slicing a string and string indexing method.

 

Further Reading

Python strings
Python substrings
String slicing

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment