In the first example the index method returns 0 because the string ‘This’ is found at index zero of our string. > 'This is a string'.index('not present') Let’s see an example: > 'This is a string'.index('This') The string index method in Python returns the index in our string where the substring is found, otherwise it raises a ValueError exception In the output of the help command you will see that one of the methods we can use to find out if a substring is part of a string is the index method. One way to do that is by looking at the methods available for string data types in Python using the following command in the Python shell: > help(str) I want to see how else I can find out if a substring is part of a string in Python. You can also use the in operator to check if a Python list contains a specific item. To reverse the logic of this if else statement you can add the not operator. This expression can be used as part of an if else statement: > if 'This' in 'This is a string': > 'This' in 'This is a string'Īs you can see the in operator returns True if the string on its left is part of the string on its right. The first option available in Python is the in operator. Conclusion In Operator to Check if a Python String Contains a Substring.Find the First Match in a String From a Python List.Identify Multiple String Matches with a Regular Expression.Check If a String Contains Any or All Elements in a List.Checking For Multiple Substrings in a String Using a List or Set Comprehension.Check If a Python String Contains Multiple Substrings. ![]() Insensitive Search For Substring in a Python String.Search For Substring in a Python String Using a Regular Expression. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |