无法检查字符串是否是python中另一个字符串的子字符串

2024-06-13 22:37:56 发布

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

我是python的初学者,我有两个字符串变量,叫做

user_comment = "Hobbit 2013:Bad Movie"
comment_in_movie = "Hobbit 2013 user@gmail.com:Bad Movie"

我试图使用以下方法检查用户注释是否在第二个变量中:

if user_comment in comment_in_movie:
     print("found")

更详细地说,我试图检查第二个字符串中是否存在上述所有单词。 但我没有得到任何结果。我认为问题在于,用户字符串在第二个字符串中的显示方式不同,因为在"2013"":Bad Movie"之间有更多的单词 如果您能帮助我解决这个简单的任务,我将不胜感激。 先谢谢你


Tags: 方法字符串incomif检查用户commentmovie
3条回答

当然,用户注释不在电影中的注释中,您需要按空格分割用户注释,然后搜索每个单词。以下是解决方案:

  if all(x in comment_in_movie for x in user_comment.split(" ")):
    print ("found")

你的假设确实是正确的。只有找到精确的字符串,字符串才会匹配。您可以这样做:

user_comment = "Hobbit 2013:Bad Movie"
comment_in_movie = "Hobbit 2013 user@gmail.com:Bad Movie"

for string in user_comment.split(":"):
    if string in comment_in_movie:
        print(f"Found '{string}' in comment_in_movie.")

这将输出:

Found 'Hobbit 2013' in comment_in_movie.
Found 'Bad Movie' in comment_in_movie.

如果要检查单个单词,可以将:分隔符替换为,并按拆分字符串:

user_comment = "Hobbit 2013:Bad Movie"
comment_in_movie = "Hobbit 2013 user@gmail.com:Bad Movie"

for string in user_comment.replace(":", " ").split(" "):
    if string in comment_in_movie:
        print(f"Found '{string}' in comment_in_movie.")

将输出:

Found 'Hobbit' in comment_in_movie.
Found '2013' in comment_in_movie.
Found 'Bad' in comment_in_movie.
Found 'Movie' in comment_in_movie.

您还可以使用^{}向您返回一个TrueFalse,它将告诉您是否存在所有字符串。这可以在一行中完成,如下所示:

user_comment = "Hobbit 2013:Bad Movie"
comment_in_movie = "Hobbit 2013 user@gmail.com:Bad Movie"

in_str = all(x in comment_in_movie for x in user_comment.replace(":", " ").split(" "))
print(in_str)

上面将输出True。您会注意到,如果在电影名称部分将user_comment改为Dark Knight,您将得到False作为输出

您自己的回答是正确的。现在您可以通过许多步骤解决此问题:

  1. 将字符串存储为一个列表,该列表中的元素等于字符串中用空格分隔的单词,并使用循环检查第一个字符串的元素是否存在于第二个字符串中。但此方法的问题是,即使第一个字符串的元素存在于第二个字符串中,也返回true,即使第一个字符串的元素存在于第二个字符串中错误的顺序…希望你能得到答案。如果你不知道循环,你可以从不同平台上提供的大量教程中学习它们,或者发短信回来

相关问题 更多 >