Introduction
The article explains a few important Substring related operations in Python like finding the substring in a string, replacing a string with another string, searching for a string using the ‘in’ operator, counting, and mathematical operations like adding two strings or using * operator with Strings. Let’s explore.
find and rfind
The python ‘find’ function finds the first occurrence of the string given in the ‘find’ function. If the substring is found the index of the first occurrence is returned else -1 is returned. Consider a String s and its memory representation
s = "MY NAME IS MARK"
s = "MY NAME IS MARK"
s.find("IS")
returns 8 as the find method returns the index of the first occurrence which is 8
s = "MY NAME IS MARK"
s.find('?')
returns -1, as ? is not present in string s.
s = "MY NAME IS MARK"
s.find('A')
returns 4
s = "MY NAME IS MARK"
s.find('AM')
returns 4 as the first occurrence of “AM” is at 4.
rfind
The rfind function returns the last occurrence of the substring if found, -1 if not found.
s = "MY NAME IS MARK"
s.rfind("A")
returns 12 as the last occurrence of “A” is the index 12
s = "MY NAME IS MARK"
s.rfind('M')
returns 11
in operator
Pythons ‘in’ operator is used to check whether a substring exists in the string or not, if the substring exists in the string True is returned else False
s = "MY NAME IS MARK"
"MAR" in s
returns True
s = "MY NAME IS MARK"
"ARK" in s
returns True
s = "MY NAME IS MARK"
'SAM' in s
returns False.
count
The count function is used to count the number of times a substring exists in a string.
s = "MY NAME IS MARK"
s.count("A")
“A” appears twice in a string hence 2 is returned
s = "MY NAME IS MARK"
s.count("M") # returns 3
s.count("MARK") # returns 1
+ and * with Strings
The + operator concatenates the strings.
"SAM" + "EER" # returns 'SAMEER'
"MY" + "NAME" + "IS" + "MARK" # returns "MYNAMEISMARK"
+ operator when used with String and an Integer throws an error
"SAM" + 2
The * operator is used with strings for repetition, for example, “a” * 2 will return “aa”. The * operator should only be used with String and an Integer, if two string uses * like “A” * “A” will throw an error.
split
The split function is used to create a list of substrings from a string.
s = "MY NAME IS MARK"
s.split()
returns ['MY', 'NAME', 'IS', 'MARK']
replace
The replace function replaces a string with another string. Syntax: string.replace(old, new)
s = "MY NAME IS MARK"
s.replace("MARK", "JOHN") # returns 'MY NAME IS JOHN'
Summary
The article covers the basic substring functions in Python like ‘find’, ‘rfind’, ‘count’, ‘replace’, ‘slice’ and how to use mathematical operators like + and * with strings.