繁体   English   中英

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

[英]Search for a set of letters in a given string - Python

我正在尝试检查emblem是否包含在userString 为了使emblem包含在userStringemblem的字符应出现在userString

Python代码如下:

emblem = "mammoth"
userEntered = "zmzmzmzaztzozh"

print(emblem)
print(userEntered)

found = emblem in userEntered

print(found)

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

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

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

substring in string

要么

emblem in userEntered

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

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

emblem = "Mammoth"

userEntered = "zmzmzmzoztzozh"

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

如果未找到,find()函数将返回-1,否则将返回第一次出现的位置,因此使用此函数可以解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM