简体   繁体   中英

Python: Identifying whether all characters of a word are present in a single string

I am a python user. I want to check whether a particular word contains characters from a string.

For example i have a word "mizaner". All its characters are present in the string "randomnizer".

I can identify whether a particular substring is part of a string eg. i can verify if "random" is part of "randomnizer" by using the if 'random' in 'randomnizer': statement but I cannot do the same for "mizaner" as even though all its characters are found in "randomnizer", the characters are jumbled up and the word cannot be used as a substring. Any suggestions ?

The Boolean expression

set('mizaner') <= set('randomnizer')

will return True since all the letters of the first string are in the second string. A similar expression will return False if there are any letters in the first string that are not in the second string.

This works because converting a string to a set removes duplicate characters and makes the order of the characters not matter, which is just what you want. The less-than-or-equal-to comparison for sets tests for the subset relation.

To handle cases where character counts matter, not just presence of characters, you'd want:

from collections import Counter

word = "randomnizer"
searchlets = "mizaner"
if not (Counter(searchlets) - Counter(word)):
    # All the letters in searchlets appeared in word

If count doesn't matter, as others have noted:

if set(searchlets).issubset(word):

will do the trick. Using issubset instead of set(searchlets) <= set(word) is slightly better theoretically, since the implementation could choose to avoid converting word to a set at all and simply stream it by with short-circuiting if the subset condition becomes impossible midway through. In practice, it looks like CPython internally converts non- set arguments to set anyway , so unless the implementation changes, both approaches are roughly equivalent.

you can use:

set(word).issubset(string)

..

word="mizaner"
string="randomnizer"
if set(word).issubset(string):
    print("All characters in word is in string")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM