字符串包含特定字符

时间:2014-04-20 00:48:37

标签: python

如果我有以下内容:

name="paula"

list=["l", "p"]

for x in list:
    print name.count(x)

>>>
1
1

如果我理解正确,请使用字符串:"paula"并确认其中包含一个"l"和一个"p"字符。

但如果我想这样做怎么办:

#**if name has both Letters, l and p, then it is a mouse**

name="paula"

list_1=["l"]
list_2=["p"]
list_3=["l", "p"]

for y in list_3:
    if name.count(y):

   print "%s contains the letters %s and %s. %s is a mouse." % (name,w,x,name)  

#assume w and x are already defined


>>>

paula contains the letters l and p. paula is a mouse.
paula contains the letters l and p. paula is a mouse.

显然,这不起作用。我意识到在这段代码中,它会检查字符"paula"的字符"l"。然后再次运行以查看它是否包含"p"。因此两个输出而不是一个。

我认为可能需要丢弃for循环。

任何帮助都是值得赞赏的人!

@ Two-Bit Alchemist- 3个列表的原因:

#cat, dog, mouse
#if name contains the letter "L", then it is a cat
#if name contains the Letter "P", then it is a dog
#if Name has both Letters, L and P, then it is a mouse
#if Name has no L or P, then loop the question


name="lily"
name_2="patrick"
name_3="paula"

list_1=["l"]
list_2=["p"]
list_3=["l", "p"]


for w in list_1:
    if name.count(w):
        print "%s contains the letter %s. %s is a cat." %(name,w,name)

for x in list_2:
    if name_2.count(x):
        print "%s contains the letter %s. %s is a dog." %(name_2,x,name_2)

for y in list_3:
    if name_3.count(y):
        print "%s contains the letters %s and %s. %s is a mouse." %(name_3,w,x,name_3)

3 个答案:

答案 0 :(得分:3)

我认为你最好的选择是使用套装。

name = 'paula'
seek = 'pl'

if set(seek).issubset(set(name)):
    print "{0} contains the letters '{1}'. {0} is a mouse.".format(name, seek)

>>> paula contains the letters 'pl'. paula is a mouse.

答案 1 :(得分:3)

如果我理解正确,你想检查是否可以在另一个字符串中找到字符串列表?

如果是这样,你可以这样做:

list3 = ["l", "p"]
name = "paula"
if all(char in name for char in list3):
    print "{0} is a mouse.".format(name)

基本上,代码的工作原理是它使用了一个与'all'运算符结合的生成器。

代码段char in name for char in list3将遍历list3中的每个项目,并将报告真值或假值,无论该字符是否存在于名称中。此语法称为生成器理解,与列表推导非常相似,您可以了解有关here的更多信息。

简而言之,char in name for char in list3正在做类似以下的事情:

temp = []
for char in list3:
    temp.append(char in name)
print temp

>>> [True, True]

接下来,all函数是一个内置函数,它接受一个bool列表,并且只有当列表中的每个元素都是True时才返回True

总而言之,只有在all(char in name for char in list3)内找到列表中的每个字符时,表达式True才会评估为name

答案 2 :(得分:1)

使用any()检查列表中的内容是否存在于字符串中:

name = "paula"
list_1 = ["l", "p"]
if any(word in name for word in list_1):
    print 'paula is a mouse'