0

if I have a str and the I use str.index(char) and the char does not exist, is it possible with one line to assign another char to the variable?

Maybe like this

str = "bar/foo"

t = str.index("_") | "Empty"

str dosen't contain _ , so the string "Empty" should be assigned instead.

vandelay
  • 1,415
  • 4
  • 28
  • 48

1 Answers1

2

Since str.index() would throw a ValueError if substring is not in a string, wrap it into an if/else checking the presence of substring in a 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
alecxe
  • 414,977
  • 106
  • 935
  • 1,083