Python Check Whether a String Contains a Substring
In Python, we can use in keyword to determine whether a string contains a substring. This method is simple and intuitive.
Example
Define a string
main_string
=
"Hello, welcome to the world of Python programming."
Define the substring to look for
sub_string
=
"Python"
Use the in keyword to check whether the substring exists in the main string
if
sub_string
in
main_string:
(
f
"'{sub_string}' is found in the main string."
)
else
:
(
f
"'{sub_string}' is not found in the main string."
)
Code analysis:
main_stringis the main string we need to check.sub_stringis the substring we are looking for.- Use
inkeyword to determine whethersub_stringwhether it exists among the keys ofmain_string. If it exists, returnTrue; otherwise, returnsFalse。 - Based on the result, print the corresponding message.
Output result:
'Python' is found in the main string.
Python3 Examples