简体   繁体   English

试图在python中比较两个字符串

[英]Trying to compare two strings in python

I even used print statements to check if y.name and favourite were the same when checking this and they were yet it still wasn't entering the if statement when using 我什至在使用print语句检查y.name和收藏夹时是否相同,但是使用它们时仍然没有输入if语句

if y.name == favourite 

or 要么

if favourite ==y.name

I'm super confused as to why that is since I thought this was just a standard equality check (The beginning of the code is mostly set up, just included it for context in the case that there was a problem there and not the if statement). 我对为什么这样做感到非常困惑,因为我认为这只是一个标准的相等性检查(代码的开头大部分是设置好的,在出现问题的情况下仅将其包括在上下文中,而不是if语句)。 Thank you in advance! 先感谢您!

class Anime(object):
    name: str = ""
    year_aired = 0
    genre1: str = ""

    def __init__(self, name, genre1, year_aired):
        self.name = name
        self.genre1 = genre1
        self.year_aired = year_aired


def _make_anime(name, genre1, year_aired):
    anime = Anime()
    return anime


animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
    if i.find("*") != -1:
        animearr[numanime].genre1 = i
    else:
        k = Anime("","", 2018)
        k.name = i
        animearr.append(k)
        numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
    if y.name == favourite:
        favgenre = y.genre1
print(favgenre)

I think you should add strip.("\\n") before you compare two string. 我认为您应该在比较两个字符串之前添加strip。(“ \\ n”)。

class Anime(object):
    name: str = ""
    year_aired = 0
    genre1: str = ""

    def __init__(self, name, genre1, year_aired):
        self.name = name
        self.genre1 = genre1
        self.year_aired = year_aired


def _make_anime(name, genre1, year_aired):
    anime = Anime()
    return anime


animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
    if i.find("*") != -1:
        animearr[numanime].genre1 = i
    else:
        k = Anime("","", 2018)
        k.name = i
        animearr.append(k)
        numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
    if y.name == favourite.strip("\n"):

        favgenre = y.genre1
print(favgenre)

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

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