Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a String Contains a Substring

Python Check Whether a String Contains a Substring

Document Object Reference Manual Python3 Examples

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:

   

print

(

f

"'{sub_string}' is found in the main string."

)

else

:

   

print

(

f

"'{sub_string}' is not found in the main string."

)

Code analysis:

  1. main_string is the main string we need to check.
  2. sub_string is the substring we are looking for.
  3. Use in keyword to determine whether sub_string whether it exists among the keys of main_string . If it exists, return True; otherwise, returns False。
  4. Based on the result, print the corresponding message.

Output result:

'Python' is found in the main string.

Document Object Reference Manual Python3 Examples