String Operators in Python Programing - Coderz*United

String Operators in Python Programing




Checking Membership Operator



We can check if a string or character is a member of another string or not using ‘in’ or ‘not in’ operators.
The ‘in’ operator returns True if the string or character is found in the main string. Returns False if not found. ‘not in’ operator returns False if a string or character is not found in the main string. Returns True otherwise. 

Ques: A Python program to find whether a substring exists in the main string or not. 


Checking Membership Operator

Results

“a” in “heya”

True 

“jap” in “heya”

False 

“jap” in “japan” 

True 

“jap” in “Japan” 

False 

“jap” not in “Japan”

True   

“123” not in “hello”

True  

“123” not in “12345” 

False



To Check the number of sub members of any word:

So to calculate the number of sub members of any word we have a special formula ie; 2n – 1

Where n is the number of letters in the word.
Eg:   “hey” -> “h”, “e”, “y”, “he”, “ey”, “hy”, “hey”

Here the word “hey” has  3 letters in it, therefore the number of sub members in it is 23 – 1  = 8 - 1 ie; 7, that means “hey” will have 7 sub members. 


Comparing Strings 

Relational operators like >, >=, <, <=, == or != can be used to compare two strings. They either return True or False(Boolean values). 

Comparison is done on the basis of Unicode values (called ordinal value). ord(‘a’)-> 97 


Characters 

Ordinal Value

0-9 

48-57 

‘A’ to ‘Z’ 

65-90 

‘a’ to ‘z’ 

97-122 



Example Code: Program to check whether the two strings are similar or not.



Comparing Strings

Results

“a”==”a” 

True

“abc”==”abc”

True

“a”!=”abc” 

True 

“A”!=”a”

True

“ABC”==”abc”

False   

“abc”!=”Abc”

True

‘a’<’A’ 

False

‘ABC’>’AB’

True

‘abc’<=’ABCD’

False

‘abcd’>’abcD’ 

True

‘abc’<’a bc’

False