Python Substring | Substring Operations in Python

Python substring is a string that is part of another (or larger) Python String. In Python Programming, this method is also known as the slicing of string.

How to Create a Python Substring

There are generally two methods of creating substrings in Python Programming Language.

  1. Slice
  2. Split

Creating Python Substring Using Slice Method

  • First, you have to store a string in a Python variable. Our example is:
    str = “Hello world this is Karan from Python Pool”
  • With the command “str [4:]” you will now output the string without the first four characters:
    ‘o world this is Karan from Python Pool’
  • With the command “str [: 4]” in turn, only the first four characters are output:
    “Hell”
  • The command “str [: – 2]”, which outputs the string without the last two characters, is also very practical:
    Hello world this is Karan from Python Po”
  • This also works the other way round, “str[-2:]” so that only the last two characters are output:
    “ol”
  • Finally, you can also combine the commands. For example, the command “x [4: -4]” outputs the string without the first and last four characters:
    ‘o world this is Karan from Python ‘

You can Execute all the above commands in the Python terminal, like the picture shown below.

Python Terminal

Creating Python Substring Using Split Method

Split strings is another function that can be applied in Python let see for the string “Python Pool Best Place to Learn Python”. First here we will split the string by using the command word. split and get the result.

word="Python Pool Best Place to Learn Python" 
print(word.split(' '))

Output

['Python', 'Pool', 'Best', 'Place', 'to', 'Learn', 'Python']

To understand this better we will see one more example of split, instead of space (‘ ‘) we will replace it with (‘r’) and it will split the string wherever ‘r’ is mentioned in the string

word="Python Pool Best Place to Learn Python " 
print(word.split('r'))

Output

['Python Pool Best Place to Lea', 'n Python ']

Note: In Python, Strings are immutable.

Python String Methods

A method in Python is similar to a function, but it runs “on” an object. If the variable s is considered as a string, then the code s.lower() runs the lower() method on that string object and then returns the result (this concept of a method running on an object is one of the basic ideas that make up Object-Oriented Programming, OOP)

Python substring has quite a few methods that string objects can call in order to perform frequently occurring tasks (related to string). For example, if you require the first letter of a string to be capitalized, you can use capitalize() method. Below are all methods of string objects. Also, all built-in functions that can take a string as a parameter and perform some task are included.

Table Containing all Python String Methods

MethodDescription
Python String capitalize()Converts first character to Capital Letter
Python String center()Pads string with the specified character
Python String casefold()converts to case folded strings
Python String count()returns occurrences of a substring
Python String endswith()Checks if String Ends with the Specified Suffix
Python String expandtabs()Replaces Tab With Spaces
Python String encode()returns encoded string
Python String find()Returns the index of the first occurrence of a substring
Python String format()formats string
Python String index()Returns Index of the Python Substring
Python String isalnum()Checks Alphanumeric
Python String isalpha()Checks if All are Alphabets
Python String isdecimal()Checks Decimals
Python String isdigit()Checks Digits
Python String isidentifier()Checks for Valid Identifier
Python String islower()Checks if all are Lowercase
Python String isnumeric()Checks Numeric
Python String isprintable()Checks Printable
Python String isspace()Checks Whitespace
Python String istitle()Checks for Titlecased
Python String isupper()returns if all are uppercase
Python String join()Returns Concatenated String
Python String ljust()returns left-justified string
Python String rjust()returns right-justified string
Python String lower()returns lowercased string
Python String upper()returns uppercased string
Python String swapcase()swap uppercase to lowercase
Python String lstrip()Removes Leading
Python String rstrip()Removes Trailing
Python String strip()Removes Both Leading and Trailing
Python String partition()Returns a Tuple
Python String maketrans()returns a translation table
Python String rpartition()Returns a Tuple
Python String translate()returns mapped string
Python String replace()Replaces Substring Inside
Python String rfind()Returns the Highest Index of the Substring
Python String split()Splits String from Left
Python String rsplit()Splits String From Right
Python String startswith() Checks if String Starts with the Specified String
Python String title()Returns a Title Cased String
Python String zfill()Returns a copy of String Padded With Zeros
String Methods

Extracting Substring in Python

We can extract substrings in Python with square brackets that may contain one or two indices and a colon. Like so,

  • myString[0] extracts the first character;
  • myString[1:] the second through last characters;
  • myString[:4] extracts the first through fourth characters;
  • myString[1:3] the second through third characters;
  • myString[-1] extracts the last character.

Must Read: Python Book | Best Book to Learn Python

How to check if a string contains a substring in Python

No matter whether it’s just a word, a letter or a phrase that you want to check in a string, with Python you can easily utilize the built-in methods and the membership test in operator.

It is worth noting that you will get a boolean value (True or False) or an integer to indicate if the string contains what you searched for. You’ll know more about it as I show the code below.

Let us take a look at the potential solutions with the help of which you can find if a string or substring in Python contains a specific word/letter.

  1. By using find() method
  2. Using in operator
  3. By using count() method
  4. Using operator.contains() method
  5. By using Regular Expressions (REGEX)

1. Python Substring using the find method

Another method you can use is the string’s find method.

Unlike the in operator which is evaluated to a boolean value, the find method returns an integer.

This integer is essentially the index of the beginning of the substring if the substring exists, otherwise, -1 is returned.

Let’s see the find method in action.

>>> str = "Messi is the best soccer player"
>>> str.find("soccer")
18
>>> str.find("Ronaldo")
-1
>>> str.find("Messi")
0

One cool thing about this method is you can optionally specify a start index and an end index to limit your search within.

2. Using the in operator to find Python Substring

The in operator returns true if the substring exists in a string and false if ​otherwise.

Syntax

The general syntax is:

substring in string

Example

a_string="Python Programming"
substring1="Programming"
substring2="Language"
print("Check if "+a_string+" contains "+substring1+":")
print(substring1 in a_string)
print("Check if "+a_string+" contains "+substring2+":")
print(substring2 in a_string)

Output

Check if Python Programming contains Programming:
True
Check if Python Programming contains Language:
False

3. By using count() method

The count() for Finding or searching Python substring method checks for the occurrence of a substring in a string. If the substring is not found in the string, it returns 0.

Syntax: string.count(substring)

Example: Checking for the presence of substring within a string using count() method

str="Python Pool is the Best Place to Learn Python"
sub1="Python"
sub2="Pool"
sub3="Done"
print(str.count(sub1)) 
 
print(str.count(sub2))
 
print(str.count(sub3))

Output:

2
1
0

4. Using Contains Method

__contains__() is another function to help you to check whether a string contains a particular letter/word.

Here’s how you can use it:

stringexample = "kiki"
stringexample.__contains__("k")

You will get the output as True/False. For the above code snippet, you will get the output as:

True

Do note that there are 4 underscore symbols involved when you want to write the method (2 before the word and 2 after).

Here’s a program to explain the same:

stringexample = "kiki"
if stringexample.__contains__("k") == True:
  print ("Yeyy, found the substring!")
else:
  print ("Oops, not found!")

In this case, the output is:

Yeyy, found the substring!

5. Using Regular Expressions (REGEX) to Find Python Substring

Regular expressions provide a more flexible (albeit more complex) way to check python substrings for pattern matching. Python is shipped with a built-in module for regular expressions, called re. The re module contains a function called search, which we can use to match a substring pattern as follows:

from re import search

fullstring = "StackAbuse"
substring = "tack"

if search(substring, fullstring):
    print "Found!"
else:
    print "Not found!"

This method is best if you are needing a more complex matching function, like case insensitive matching. Otherwise, the complication and slower speed of regex should be avoided for simple substring matching use-cases.

Example of Alternate Characters Substrings in Python

You can also use the same slicing concept in python to generate substrings by forming a lot more logics. The following lines of code will help you form a string by choosing the alternate string characters.

fullString = "Alternate Characters"
#Choose Alternate Characters & Forms the SubString
subString = fullString[::2] #Basically we're selecing every 2nd chracter
print(subString)

Output

AtraeCaatr

Python Substring using For Loop

You can also use for loop with range function to return a substring.  For this, we have to use print function along with end argument. This Python string example returns a substring starts at 3 and ends at 24.

string = 'Python Programming Language for Free'
 
for n in range(3, 25):
    print(string[n], end = '')

Python substring match

In this example, we check whether the substring is present in the given string or not using the Python If Else and not In operator.

string = 'Hello World'
 
substring = 'Hello'
 
if substring not in string:
    print('We haven\'t found what you are looking for = ', substring)
else:
    print('We found the Matching substring = ', substring)

Output

We found the Matching substring =  Hello

Python Program to Find all indexes of substring

There is no built-in function to get the list of all the indexes for the substring. However, we can easily define one using find() function.


def find_all_indexes(input_str, substring):
    l2 = []
    length = len(input_str)
    index = 0
    while index < length:
        i = input_str.find(substring, index)
        if i == -1:
            return l2
        l2.append(i)
        index = i + 1
    return l2


s = 'This Is The Best Theorem'
print(find_all_indexes(s, 'Th'))

Output

[0, 8, 17]

Summary:

Since Python is an object-oriented programming language, many functions can be applied to Python objects and Python Substring. A notable feature of Python is its indenting source statements to make the code easier to read.

  • Accessing values through slicing – square brackets are used for slicing along with the index or indices to obtain a substring.
    • In slicing, if the range is declared [1:5], it can actually fetch the value from the range [1:4]
  • You can update Python String by re-assigning a variable to another string
  • Method replace() returns a copy of the string in which the occurrence of old is replaced with new.
    • The syntax for method replaces oldstring.replace(“value to change”,”value to be replaced”)
  • String operators like [], [: ], in, Not in, etc. can be applied to concatenate the string, fetching or inserting specific characters into the string, or to check whether certain character exist in the string

With slices or Python Substring, we extract parts of strings. We can specify an optional start index and an optional last index (not a length). Offsets are useful.

If you still have any doubt or confusion, do let us know in the comment section below.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments