我试图得到这样的输出:

I dont want ANY spam
I dont want ANY spam
I dont want ANY spam


使用此代码:

wife = 'spam spam spam'
[print('i dont want ANY spam') for x in wife if 'spam' in wife]


但是我得到了:

I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam
I dont want ANY spam


每当看到变量妻子发出垃圾邮件一词时,我只需要打印出来,我该怎么做?

最佳答案

for x in wife.split():
    if x == "spam":
        print ("I dont want ANY spam")


试试这个。您要遍历wife的每个字母而不是每个单词。 .split()使其遍历每个单词。

或者您可以尝试:

print ("I dont want ANY spam \n" * wife.count("spam"))

关于python-3.x - Python每次在字符串中找到特定单词时如何打印字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50847224/

10-12 17:21