Check if a substring is present in a string variable that may be set to None

Question:

I have a string named brand that can be None or contain a value. How can I search for a substring within it when it is None?

By putting an additional if-statement to check if the brand is for None before searching the substring works, but is there a better way?

### When the string brand contains a value ###
brand = "Vans.com"
if("Vans" in brand):
   print("Y")
else:
   print("N")
# output - Y


### When the string brand is None ###
brand = None
if("Vans" in brand):
   print("Y")
else:
   print("N")
# output - TypeError: argument of type 'NoneType' is not iterable. 


### After putting  an additional check ###
brand = None
if (brand is not None):
  if("Vans" in brand):
     print("Y")
  else:
     print("N")

# No output
Asked By: M J

||

Answers:

You can use the and operator to avoid nesting if statements.

if brand and "Vans" in brand:

Alternatively, it may work to replace None with an empty string before attempting to use the string.

brand = brand or ''
if "Vans" in brand:
Answered By: Unmitigated

Also try/except would work

try:
   print('y' if 'vans' in brand else 'n')
except:
   pass
Answered By: Diego Torres Milano

Casting brand to a string object.

brand = None

match = "Vans"
if match in str(brand):
    print('Y')
else:
    print('N')

Eventually, take advantage of str-methods such as str.find

brand = None

match = "Vans"
if str(brand).find(match):
    print('N')
else:
    print('Y')
Answered By: cards
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.