![]() ![]() 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 much more efficient to use the in comparison operator.Īlso, these are not drop-in replacements for in. Testing if "substring" in "a string with a substring inside"ĭon't use find and index to test for "contains"ĭon't use the following string methods to test for "contains": > '**foo**'.index('foo') Ns = NoisyString('a string with a substring inside') Return super(NoisyString, self)._contains_(other) if subclassing str): class NoisyString(str): The only reason to use this is when implementing or extending the in and not in functionality (e.g. Methods that start with underscores are considered semantically non-public. ![]() You could also call this function from the instance of the superstring: '**foo**'._contains_('foo')īut don't. The "contains" method implements the behavior for in. This is semantically the same as not 'foo' in '**foo**' but it's much more readable and explicitly provided for in the language as a readability improvement. The opposite (complement), which the original question asked for, is not in: > 'foo' not in '**foo**' # returns False other Python programmers will expect you to use it.Or str.index (like find but raises ValueError on failure): start = 100Īny_string.index('substring', start, end) Does Python have a string contains substring method?ĩ9% of use cases will be covered using the keyword, in, which returns True or False: 'substring' in any_stringįor the use case of getting the index, use str.find (which returns -1 on failure, and has optional positional arguments): start = 0Īny_string.find('substring', start, stop)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |