python strings part 2 i-sapna

Python Strings – Part 2

Welcome to another chapter of our Python tutorial series, Learn Python with me. In the previous chapter, we began looking at the concepts of Strings and Characters in detail. That’s why, if you are visiting our blog for the first time to read about the Python Strings, you might want to read our previous chapter first.

The chapter on this post is again the continuation of the same topic. In this post, we will discuss checking the membership of a string, comparing strings, removing spaces from the string, counting substrings in a string, finding substrings in a string, and the immutable property of the string.


Our entire Python tutorial: Learn Python


How to check the membership of a string?

  • Python allows you to check whether a character or string is part of another string using the ‘not in‘ and ‘in‘ operators.
  • If the string or character is found in another string using the ‘in‘ operator, it will return True. If the character or string is not found using the ‘in‘ operator on another string, the result will be False.
  • Using the ‘not in‘ operator, it will return False if the string or character is found on another string, and it will return True if the string or character is not found on another string.

Let us look at an example program to understand this concept better. Let us take the main string and a sub-string as input from the user’s keyboard in this program. And on the following line, let us add the code to see if the sub-string is part of the main string.

#check whether sub-string is part of the main string
main_string=input('Please enter main string')
sub_string=input('Please enter sub string')
if sub_string in main_string:
    print(sub_string+' is found in the main string')
else:
    print(sub_string+' is not found in the main string')

Output

Please enter main stringBusiness Analytics
Please enter sub stringBusiness
Business is found in the main string

How to compare Strings?

Using the relational operators such as >, <, >=, <=, !=, or ++ you can compare any two strings in Python. The result would be True or False based on the logic you add to compare the strings. For example, let us consider the program below.

string1='Apple'
string2='Google'
if(string1==string2):
    print(string1 +' and '+ string2 +' are the same strings')
else:
    print(string1 +' and '+ string2 +' are two different strings')

string3='Microsoft'
string4='Microsoft'
if(string3==string4):
    print(string3 +' and '+ string4 +' are the same strings')
else:
    print(string3 +' and '+ string4 +' are two different strings')

Output

Apple and Google are two different strings
Microsoft and Microsoft are the same strings

How to remove spaces from a string?

Python considers the space also as the part of the string. That’s why if you compare two similar strings with additional space on one of the strings, it will return False.

string1='Apple   '
string2='Apple'
if(string1==string2):
    print(string1 +' and '+ string2 +' are the same strings')
else:
    print(string1 +' and '+ string2 +' are two different strings')

Output

Apple    and Apple are two different strings

The example program mentioned above is an excellent reminder to aspirant programmers like us to understand the importance of spaces in Python. Though both the declared strings contain the text ‘Apple’, the spaces are different on both the string variables and that’s why the output displays that they are different strings.

Now, if you want to compare only the characters, you should remove the spaces. Python provides you with strip(), lstrip(), and rstrip() methods to assist you in removing the spaces.

strip() methodThis will trim the spaces on the left and right sides of the string
lstrip() methodThis will trim the spaces on the left side of the string
rstrip() methodThis will trim the spaces on the right side of the string

Let us look at an example to understand the concepts of trimming the spaces in a Python program.

actor='   Brad Pitt   '
print(actor.strip()) #remove spaces from both sides
print(actor.rstrip()) #removes spaces on the right side
print(actor.lstrip()) #removes spaces on the left side

Output

Brad Pitt
   Brad Pitt
Brad Pitt

How to find positions of Sub Strings?

  • If you want to locate a substring in any string, you can make use of the find(), rfind(), index(), and rindex() methods.
  • While the find() and index() methods begin the search from the beginning of a string, the rfind() and rindex() methods start the search from the ending of a string to its beginning.
  • If the find() method doesn’t find a substring in the main string, it will return -1. And if the index() method doesn’t find a substring in the main string, it will return ‘ValueError’ exception
The format of the find() method is mainstring.find(substring, beginning, ending)
#program to find first occurrence of sub string in main string
main_string=input('Please enter main string')
sub_string=input('Please enter sub string')

#find the position of sub string in main string
#search from 0th to last characters in main string
num=main_string.find(sub_string, 0, len(main_string))

#since the find() returns -1 if sub string is not found
if num==-1:
    print("Entered substring is not found")
else:
    print("Substring is found at the position: ",num+1)

Output

Please enter main stringThis is a mouse
Please enter sub stringmouse
Substring is found at the position:  11

Since the find() method begins the count from the 0th location, we counted from the 1st position to get the accurate location of the number in the above program. That’s why we added n+1 in the above program’s logic.

You can rewrite the same program using the index() method as mentioned in the program below. Since the index() method throws ‘ValueError’ exception, we should also add code to handle the exception. Please do not get confused about the concept of Exception handling, we will cover it in detail in our future chapters.

#program to find first occurrence of sub string in main string
main_string=input('Please enter main string')
sub_string=input('Please enter sub string')

#find the position of sub string in main string
#search from 0th to last characters in main string
try:
    num=main_string.index(sub_string, 0, len(main_string))
except ValueError:
    print("Entered substring is not found")
else:
    print("Substring is found at the position: ",num+1)

Output

Please enter main stringAmazing feeling correct?
Please enter sub stringfeeling
Substring is found at the position:  9

The logic mentioned above can also be used to search the positions in the reverse order by using the rfind() and rindex() methods.

How to count Substrings in a string?

If you want to know how many times a Substring has appeared in the string, you should use the count() method for the same. Please find below the format to use the count method.

stringname.count(substring)
main_string='sony speakers'
num=main_string.count('speakers')
print(num)

Output

1

The program above displayed the number of times speakers appeared in the main string as the output. And it is 1.

If you want to know the number of times the character ‘s’ appears on the main string, you should enter the code as mentioned below.

main_string='sony speakers'
num=main_string.count('s',0,len(main_string))
print(num)

Output

3

Python Strings are Immutable

Immutable means that you cannot change. Yes, the Python Strings are immutable like tuples. Do you want to know the significant reasons why the Python Strings are immutable? Please find them below.

  • To increase security: If you try modifying any existing string, chances are that the Python will create a new object for you in the memory. This will be helpful for the developers to understand if anyone is trying to update the strings and compromise the security in an application. That way, the developers will be alerted and the security will be improved with the immutable characteristic of a Python string.
  • To enhance performance: If an object is immutable in a program, a fixed memory is already created for them in Python. It also means that new additional memory will not be made, and that’s why the performance will be enhanced through the Python strings.
example_string='Python and Java'
print(example_string[0])

Output (Running the code above will display the first character in the declared string)

P

However, if you try updating the first character of this string to something else, an error called ‘TypeError’ will be displayed as mentioned in the program below.

example_string='Python and Java'
example_string[0]='L'

Output error

Traceback (most recent call last):
  File "E:\Python\pythonStrings\main.py", line 2, in <module>
    example_string[0]='L'
TypeError: 'str' object does not support item assignment

Source

Scroll to Top