+2 votes
2 views
in Python by (1.2k points)
edited by

Can someone tell me any string.contains or string.indexof method in Python

I want to do

if not somestring.contains("boom"):

  continue

3 Answers

+3 votes
by (10.9k points)
edited by

@James21, The “in” operator may solve your problem.

First, let’s know what a “in” operator is:

in and not in are known as membership test operators.

in          False if the value is not found in the sequence,

not in    False if the value is found in the sequence

The solution to your code is:

if "boom" not in somestring:

continue

0 votes
by (46.1k points)
edited by

The method  answered by @shrutiparana is very short and useful one, but there is one more method too, i.e. Find Method

You can use find method to return the integer 

Integer here is basically the index of the beginning of the substring it it exist, otherwise -1 is returned.

>>> str = "Boom"

>>> str.find("boom")

Hope this helps.

0 votes
by (107k points)
edited by

If you only want a substring search then you can use string.find("substring").

You can also look at the below-mentioned code:-

s = "This be a string" 

if s.find("is") == -1: 

print "No 'is' here!" 

else: 

print "Found 'is' in the string."

It would print Found 'is' in the string. Similarly, if "is" in s: would evaluate to True. This may or may not be what you want.

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Feb 3 in BI by Vaibhav Ameta (17.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...