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

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments