Python – Check if a String contains another String?

In Python, we can use in operator or str.find() to check if a String contains another String.

1. in operator


name = "mkyong is learning python 123"

if "python" in name:
    print("found python!")
else:
    print("nothing")

Output


found python!

2. str.find()


name = "mkyong is learning python 123"

if name.find("python") != -1:
    print("found python!")
else:
    print("nothing")

Output


found python!

For case-insensitive find, try to convert the String to all uppercase or lowercase before finding.


name = "mkyong is learning python 123"

if name.upper().find("PYTHON") != -1:
    print("found python!")
else:
    print("nothing")

Output


found python!

References

  1. Python doc str.find()

No comments yet. Be the first to leave a comment!

Leave a Comment

Your email address will not be published. Required fields are marked *