Python - Check if a string contains a substring

Document 对象参考手册Python3 Examples

In Python, we can use thein`in` keyword to check whether a string contains a substring. This method is very simple and intuitive.

Example

# Define a string
main_string = "Hello, welcome to the world of Python programming."

# Define the substring to search for
sub_string = "Python"

# Use the `in` keyword to check whether the substring exists in the main string
if sub_string in main_string:
    print(f"'{sub_string}' is found in the main string.")
else:
    print(f"'{sub_string}' is not found in the main string.")

Code explanation:

  1. main_stringis the main string we need to check.
  2. sub_stringis the substring we are looking for.
  3. Useinkeyword to determinesub_stringwhether it exists inmain_stringthe string. If it exists, returnTrueotherwise returnFalse。
  4. Output the corresponding message based on the result.

Output result:

'Python' is found in the main string.

Document 对象参考手册Python3 Examples

Other extensions