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

2024-09-21 03:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: of函数infalsetrue字母单词word
3条回答
>>> 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

假设您的意思是“in a word”to be“两边至少有一个字符是“word character”,那么这将起作用:

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

相关问题 更多 >

    热门问题