What's the most efficient way to find whether a group of characters, arranged in a string, exists in a string in Python?
For example, if I have string="hello world"
, and sub-string "roll"
, the function would return true because all 4 letters in "roll"
exist in "hello world"
.
There's the obvious brute-force methodology, but I was wondering if there's an efficient Python specific way to achieve this.
EDIT: letters count is important. So for example rollll
isn't included in hello world
(only three l's).
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
find() str. find() method is generally used to get the lowest index at which the string occurs, but also returns -1, if string is not present, hence if any value returns >= 0, string is present, else not present.
The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")
Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .
You could use collections.Counter
:
from collections import Counter
substring_counts = Counter(substring)
text_counts = Counter(text)
if all(text_counts[letter] >= count for letter, count in substring_counts.items()):
# All the letters in `substring` are in `count`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With