python - Second option if str.index does not exist -


this question has answer here:

if have str , use str.index(char) , char not exist, possible 1 line assign char variable?

maybe this

str = "bar/foo"  t = str.index("_") | "empty" 

str dosen't contain _ , string "empty" should assigned instead.

since str.index() throw valueerror if substring not in string, wrap if/else checking presence of substring in string via in operator:

>>> s = "bar/foo" >>> s.index("_") if "_" in s else "empty" "empty"  >>> s = "bar_foo" >>> s.index("_") if "_" in s else "empty" 3 

Comments