python检查字符串中的字母部分

时间:2013-04-15 06:53:20

标签: python

我想写一个函数来检查一个字母是否是单词的一部分,例如

"u" part of word in "i c u" = false
"u" part of word in "umbrella" = true

3 个答案:

答案 0 :(得分:6)

>>> 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(),具体取决于您是否区分大小写或

答案 1 :(得分:0)

假设你的意思是'在一个单词'中'至少有一个字符在两边是“单词字符”',这将有效:

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

答案 2 :(得分:0)

>>> word = 'i c u'
>>> letter = 'u'
>>> letter in word.split(' ')
True
>>> word = 'umbrella'
>>> letter in word.split(' ')
False