搜索给定字符串中的一组字母

2024-04-20 07:21:21 发布

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

我试图检查emblem是否包含在userString中。要使emblem包含在userString中,emblem中的字符应该出现在userString。你知道吗

Python代码如下:

emblem = "mammoth"
userEntered = "zmzmzmzaztzozh"

print(emblem)
print(userEntered)

found = emblem in userEntered

print(found)

在上面的例子中,单词mammoth确实出现在zmzmzmzaztzozh(字符maoth都在zmzmzmzaztzozh中),但是我仍然发现=false。有没有一种方法可以在Python中不使用正则表达式的情况下检查给定的单词是否出现在加扰字符串中?你知道吗


Tags: 方法代码infalse情况字符单词例子
3条回答

Python为我们提供了一个内置函数find(),它检查字符串中是否存在子字符串,这是在一行中完成的。你知道吗

emblem = "Mammoth"

userEntered = "zmzmzmzoztzozh"

if userEntered.find(emblem) == -1:
    print("Not Found")
else:
    print("Found")

如果找不到,find()函数返回-1,否则返回第一个匹配项,因此使用此函数可以解决此问题。你知道吗

要检查子字符串是否在字符串中,请使用in运算符:

substring in string

或者

emblem in userEntered

如果找到,则返回true,否则返回false

>>> from collections import Counter
... 
... 
... def solution(emblem, user_entered):
...     return not (Counter(emblem) - Counter(user_entered))
... 
>>> solution('mammoth', 'zmzmzmzaztzozh')
True
>>> solution('mammoth', 'zmzmzmzaztzoz')
False

相关问题 更多 >