简体   繁体   中英

Determining if string contains same word more than once using Python?

I have strings with owner names and I need to identify whether they contain a last name twice.

For example, I may have an owner name that reads " BENNETT MCCARL & ARNETTE BENNETT ".

I would like to return True if any word is found in the string twice, and False if all words in the string are unique.

Does anyone know how I can do this using Python?

def check(name):
    words = name.split()
    return (len(words) > len(set(words)))

You can split the name into a word list by spaces, and then transform this list into a set. Its length will become shorter after duplicated words has been eliminated.

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