Python - Check if a string contains a substring
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.")
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:
main_stringis the main string we need to check.sub_stringis the substring we are looking for.- Use
inkeyword to determinesub_stringwhether it exists inmain_stringthe string. If it exists, returnTrueotherwise returnFalse。 - Output the corresponding message based on the result.
Output result:
'Python' is found in the main string.Other extensions
Python3 Examples