I'm looking for a string.contains
or string.indexof
method in Python.
I want to do:
if not somestring.contains("blah"):
continue
|
You can use the
|
|||||||||||||||||||||
|
If it's just a substring search you can use You do have to be a little careful with
Would print |
|||||||||||||||||||||
|
If you truly need a method instead of an operator (e.g. to do some weird |
|||||||||||||
|
Not there is no
Here is more complex working example:
|
|||||
|
Basically, you want to find a substring in a string in python. There are 2 ways to search for a substring in a string in python. Method 1:
Method 2:
I would recommend you to use the first method as it is more pythonic and intuitive. |
|||||
|
Yes, but Python has a comparison operator that you should use instead, because the language intends its usage, and other programmers will expect you to use it. That keyword is
The opposite (complement), which the original question asks for, is
This is semantically the same as Avoid using the belowAs promised, here's the
returns
But don't. Methods that start with underscores are considered semantically private. The only reason to use this is when extending the
and now:
Also, avoid the following string methods:
Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is more efficient to use the
And now we see that using
is much faster than the below:
|
|||||||||
|
So apparently there is nothing similar for vector-wise comparison. An obvious Python way to do so would be:
|
|||||||||||||||||
|
Another way to find whether string contains few characters or not with the Boolean return value (i.e.
|
|||||
|
Here is your answer:
For checking if it is false:
OR:
|
||||
|
In Python there are two simple ways you can achieve this: The Pythonic way: Using Python's 'in' Keyword-
Output:
The non-Pythonic way: Using Python's str.find: The
Output:
|
|||
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?