Operators in String


☞We will perform the following operators on the string.

1. Concatenation(+) Operator
2. Replication(*) Operator
3. Membership (in,not in) Operator
4. Comparison(<, >, <=, >=, ==, !=) Operator

Concatenation(+) Operator :

  • Concatenation can be done only on string + string
Example 1 :
 
S1 = "inspire" + "web" + "soft"
print(S1)   
    
Output :
 
inspirewebsoft   
    
Example 2 :
 
S1 = "inspire" + 3
print(S1)   
    
Output :
 
S1 = "inspire" + 3
TypeError: can only concatenate str (not "int") to str       
    
Note : If you will concatenate string + datatype other than string, it will give you an error.

Replication(*) Operator :

  • Replication can be done only on string * int
Example 1 :
 
S1 = "inspire" * 3
print(S1)   
    
Output :
 
inspireinspireinspire   
    
Example 2 :
 
S1 = "inspire" * 3.5
print(S1)   
    
Output :
 
S1 = "inspire" * 3.5
TypeError: can't multiply sequence by non-int of type 'float'       
    
Note : If you will multiply string * datatype other than int, it will give you an error.

Membership (in,not in) Operator :

  • in : It returns True if an element exists in the given string; Otherwise returns False
  • not in : It returns True if an element does not exist in the given string; Otherwise returns False
Example :
 
S1 = "ins" in "inspireWEBsoft.com"
print(S1)

S2 = "web" in "inspireWEBsoft.com"
print(S2)   
    
Output :
 
True
False   
    

Comparison(<, >, <=, >=, ==, !=) Operator :

  • It starts by comparing the first element from each sequence.
  • If they are equal, it goes on to the next element, and so on, until it finds elements that differ.
  • Subsequent elements are not considered(even if they are really big).
  • int and float are considered as same.
Example :
 
S1 = 'abc' > "Abc"
print(S1)

S2 = 'abc' < "Abc"
print(S2)

S3 = 'abc' >= "Abc"
print(S1)

S4 = 'abc' <= "Abc"
print(S2)

S5 = 'abc' < "aBc"
print(S3)

S6 = 'abc' <= "aBc"
print(S6)   
    
Output :
 
True
False
True
False
True
False