1

I am doing something similar to this to output if a variable contains a substing.

print("Variable contains foo" * variable.index("foo") !=None)

But when I run the program, I just get this error.

ValueError: substring not found

Of course, I am expecting variable to not contain "foo" sometimes, so is there any way to do something like this without using try and except?

esqew
  • 42,425
  • 27
  • 92
  • 132
  • 2
    If you just want to know if `variable` contains "foo" you can use `in`: `"foo" in variable` – Iain Shelvington May 12 '21 at 01:46
  • 1
    Possible duplicate: [Does Python have a string 'contains' substring method?](https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – wjandrea May 12 '21 at 01:54
  • 1
    using `if "foo" in variable: print(...)` is more readable. – furas May 12 '21 at 02:18

4 Answers4

4

As @IainShelvington already said you can use 'foo' in variable which will never raise an Exception, or not in for opposite condition:

Try it online!

variable = 'a foo'
print("Variable contains foo" * ('foo' in variable))
variable2 = 'a bar'
print("Variable2 has no foo" * ('foo' not in variable2))

Output:

Variable contains foo
Variable2 has no foo
Arty
  • 14,883
  • 6
  • 36
  • 69
2

In despite of here present correct answers, I recommend more easy-readable and understandable variant without arithmetic operations on strings:

print('' if variable.find("foo") < 0 else 'Variable contains foo')

And don't forget about performance:

  1. A IF in ELSE B → runtime 0.075396442~0.079946904
import timeit
start = timeit.default_timer()
variable = 'foo'
for i in range(0,1000000):
  a = 'Variable contains foo' if 'foo' in variable  else ''
stop = timeit.default_timer()
print('Time: ', stop - start)
  1. IF in A*BOOL → runtime 0.098681301~0.099800959
import timeit
start = timeit.default_timer()
variable = 'foo'
for i in range(0,1000000):
  a = "Variable contains foo" * ('foo' in variable)
stop = timeit.default_timer()
print('Time: ', stop - start) 
  1. A IF find ELSE B → runtime 0.19235808~0.195008498
import timeit
start = timeit.default_timer()
variable = 'foo'
for i in range(0,1000000):
  a = '' if variable.find("foo") < 0 else 'Variable contains foo'
stop = timeit.default_timer()
print('Time: ', stop - start) 
rzlvmp
  • 7,512
  • 5
  • 16
  • 45
1

You can use Python's find, which returns -1 if the substring cannot be found:

print("Variable contains foo" * (variable.find("foo") != -1))

Note that this prints an empty line if "foo" is not present.

knosmos
  • 636
  • 6
  • 17
0

The index method raises an error if the substring is not found, whereas the find method returns -1.

"My beautiful string".index("foo")     # This raises an exception

"My beautiful string".find("foo")     # This returns -1

Then, you could just save the result and print whatever you wish.

Pergola
  • 118
  • 1
  • 5