当试图在字符串中查找字符时,字符串中的多个字符返回假布尔值

2024-09-30 01:24:06 发布

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

#Function takes a character and a string and returns a boolean reflecting if
#the character is found in the string.
def isItThereS(letter, word):
    letInWord = 0
    for l in word:
        if l == letter:
            letInWord += 1
    return letInWord == True

当我把它放在接线员的时候

isItThereS("h","hello world") True

但当我找到一个重复“l”或“o”的字符时,它返回false。在

isItThereS("l","hello world") False

我该如何让它不返回false,而是返回True,因为字符在字符串中?在


Tags: andtheinfalsetruehelloworldstring
2条回答

如果真的想为此使用自定义函数,请将返回值改为return letInWord >= 1。因为除了1 == True之外的所有内容都将计算为False。(因此,更合适的函数名是is_it_there_only_once)。在

否则请使用armak提供的解决方案。在

您可以简单地使用in运算符

def isItThereS(letter, word):
  return letter in word

相关问题 更多 >

    热门问题