我想编写一个函数来检查一个字母是否是一个单词的一部分,例如
"u" part of word in "i c u" = false
"u" part of word in "umbrella" = true
我想编写一个函数来检查一个字母是否是一个单词的一部分,例如
"u" part of word in "i c u" = false
"u" part of word in "umbrella" = true
>>> text = "i c u"
>>> letter = "u"
>>> any(letter in word and len(word) > 1 for word in text.split())
False
>>> text = "umbrella"
>>> any(letter in word and len(word) > 1 for word in text.split())
True
您可能会更改letter in word
为letter.lower() in word.lower()
取决于您是否区分大小写或nt。
>>> word = 'i c u'
>>> letter = 'u'
>>> letter in word.split(' ')
True
>>> word = 'umbrella'
>>> letter in word.split(' ')
False
假设您的意思是“在一个单词中”是“在任一侧至少有一个字符是“单词字符””,这将起作用:
import re
def letter_in_a_word(letter, words):
return bool(re.search(ur'\w{0}|{0}\w'.format(letter), words))
letter_in_a_word('u', 'i c u') # False
letter_in_a_word('u', 'umbrella') # True
letter_in_a_word('u', 'jump') # True