How to check is a sub string membership in Python

In operator

We can use in operator to check if a value is in a string. The in operator returns true if the value is found and returns false if not found.


permissions = 'rw' 
print 'w' in permissions 

The code above generates the following result.

The following code shows how to use not in operator.


print 'bc' in 'abcd'
print 'n' in 'abcd'
print 'nm' not in 'abcd'

The code above generates the following result.

We can also use in operator with for loop.


seq1 = "spam" # from  w  w w .jav  a 2s. c o m
seq2 = "scam" 

res = []                                
for x in seq1:                          
    if x in seq2:                       
        res.append(x)                   
print res 

The code above generates the following result.

To iterate over each character.


foo = 'abc'
for c in foo:
    print c
    

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary