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()

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments