Home >Backend Development >Python Tutorial >How Can I Check if a Python String Contains a Substring?

How Can I Check if a Python String Contains a Substring?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 10:48:11881browse

How Can I Check if a Python String Contains a Substring?

Python String Contains Substring Method

In Python, there is no dedicated string.contains() or string.indexof() method for checking if a string contains a substring. However, there are alternative approaches to achieve this functionality.

Using the 'in' Operator

The 'in' operator can be used to test if a substring is present within a string. It compares the substring to the entire string and returns True if it is found.

if "blah" in some_string:
    # Code to be executed if "blah" is in some_string
else:
    # Code to be executed if "blah" is not in some_string

Note: The 'in' operator is case-sensitive.

Other Alternatives

  • string.find() method: Returns the index of the first occurrence of the substring, or -1 if not found.

    index = some_string.find("blah")
  • string.startswith() method: Checks if the string starts with the specified substring.

    if some_string.startswith("blah"):
      # Code to be executed if some_string starts with "blah"
  • string.endswith() method: Checks if the string ends with the specified substring.

    if some_string.endswith("blah"):
      # Code to be executed if some_string ends with "blah"

The above is the detailed content of How Can I Check if a Python String Contains a Substring?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn