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
Release: 2024-12-22 10:48:11
Original
875 people have browsed it

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
Copy after login

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")
    Copy after login
  • 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"
    Copy after login
  • 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"
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template