String Operations in Python Part 1

In the previous article we saw the use of Formatting Strings in Python, in this article we are going to discuss operations on Strings and methods of Strings.

Working with String Operations in Python

The first operation we are going to discuss is checking whether a given string is a substring of another string or not. Let us first understand what is a substring. For example, we have a string “ABCD”. So the substrings of this particular string would be “”, “A”, “B”, “C” , “D” , “AB” , “ABC” , “ABCD” , “BC”, “BCD”, “CD”. All the consecutive characters of the given string are substrings including the empty string and the whole string itself. Consecutive characters means one one following the other, so AC would not be a sub string as they are not consecutive or in order.

We have an operator for checking whether a string is a substring. For example, the string “geeksforgeeks” and the substring “geeks”, it would be a substring as it appears twice and each time in consecutive order.-We can use the in operator to find out whether a given string appears in another string.

s1="geeksforgeeks"
s2="geeks"
print(s2 in s1)
print(s2 not in s1)
Output:
True
False

As we can see, it returns a Boolean result depending on the validity.

Concatenation of Strings

The combining (adding to the end of the other) of strings together can be done through the use of the ‘+’ operator in Python.

s1="geeks"
s2="forgeeks"
s3=s1+s2
s4="Welcome to" +s1 +s2
print(s3)
print(s4)
Output:
geeksforgeeks
Welcome to geeksforgeeks

Ignoring memory and device limitations, we can choose to concatenate as many number of strings as needed.

Finding position of Substring in Python

How can we find the particular range or index location of a substring within a given string? We can do so through the use of the index( ) and rindex( ) functions.

index( ) gives us starting index of the first position of a substring, for example we see that in the string “geeksforgeeks”, the substring “geeks” appears twice. Utilizing the index( ) function would return to us the first occurence.

Meanwhile rindex( ) would start searching from the last position in a reverse manner, and hence would return to us the starting index of second occurrence in this case. Both functions can also take additional parameters after specifying the string, that is the starting index where to look from and the end index where to stop the search.

s1="geeksforgeeks"
s2="geeks"
print(s1.index(s2))
print(s1.rindex(s2))
#Use of additional parameters
print(s1.index(s2,0,13))
Output:
0
8
0

When the additional two parameters are passed in index( ) or rindex( ) they simply ignore the part of the range which is not mentioned.

In the next article, we will look at some more String Operations

Leave a Comment