how.wtf

Check if a String Contains a Substring in Python

· Thomas Taylor

Checking if a string contains a substring is trivial in Python!

The in Operator

The in operator is the most straightforward and pythonic method.

Checking if a string has a substring:

1string = "howwtf"
2substring = "wtf"
3
4if substring in string:
5    print("exists")
1exists

Checking if a string has any substrings:

1string = "howwtf"
2substrings = ["how", "apple"]
3if any(x in string for x in substrings):
4    print("exists")
1exists

Checking if a string has all substrings:

1string = "howwtf"
2substrings = ["how", "wtf"]
3if all(x in string for x in substrings):
4    print("all exist")
1all exist

#Python  

Reply to this post by email ↪