gpt4 book ai didi

Python:查找字符串中的单词

转载 作者:行者123 更新时间:2023-12-01 07:36:36 24 4
gpt4 key购买 nike

我想在字符串中查找单词,如下所示:

kkk="I do not like that car."

if "like" in kkk:
print("like")
elif "dislike" in kkk:
print("dislike")
elif "hate" in kkk:
print("hate")
elif "cool" in kkk:
print("cool")

但是由于我的代码很长,我想将其缩短:

if "like" in kkk or "dislike" in kkk or "hate" in kkk or "cool" in kkk:
#print "like"
#unable to do it this way

然后我尝试使用另一种方式,但没有成功:

a=["like","dislike","hate","cool"]

if any(x in kkk for x in a):
print(x)
#NameError: name 'x' is not defined

最佳答案

试试这个:

>>> kkk="I do not like that car."
>>> a=["like","dislike","hate","cool"]
>>> print(*[x for x in a if x in kkk])
like

此列表理解与以下相同:

for x in a:
if x in kkk:
print(x)

关于Python:查找字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56965891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com