Python字符串赋值问题!

1 投票
2 回答
708 浏览
提问于 2025-04-16 16:51

我对Python还比较陌生,但我完全不知道为什么这个强制的oldUser在我调用parse的时候变成了当前用户。希望能得到一些帮助。

while a < 20:
    f = urllib.urlopen("SITE")
    a = a+1

    for i, line in enumerate(f):
        if i == 187:
            print line

            myparser.parse(line)
            if fCheck == 1:
                result  = oldUser[0] is oldUser[1]
                print oldUser[0]
                print oldUser[1]
            else:
                result = user is oldUser

            fCheck = 1
            print result

            user = myparser.get_descriptions(firstCheck)

            firstCheck = 1
            print user

            if result:
                print "SAME"
                array[index+1] = array[index+1] +0
            else:
                oldUser = user

        elif i > 200:
            break
        myparser.reset()

我也不明白为什么result不管用……我打印出这两个值,当它们相等时,系统却告诉我它们不相等……还有,为什么myparser.parse(line)会把oldUser变成一个大小为2的数组?谢谢!

** 这是myparse的定义……

class MyParser(sgmllib.SGMLParser):
"A simple parser class."

def parse(self, s):
    "Parse the given string 's'."
    self.feed(s)
    self.close()

def __init__(self, verbose=0):
    "Initialise an object, passing 'verbose' to the superclass."

    sgmllib.SGMLParser.__init__(self, verbose)
    self.divs = []
    self.descriptions = []
    self.inside_div_element = 0

def start_div(self, attributes):
    "Process a hyperlink and its 'attributes'."

    for name, value in attributes:
        if name == "id":
            self.divs.append(value)
            self.inside_div_element = 1

def end_div(self):
    "Record the end of a hyperlink."

    self.inside_div_element = 0

def handle_data(self, data):
    "Handle the textual 'data'."

    if self.inside_div_element:
        self.descriptions.append(data)


def get_div(self):
    "Return the list of hyperlinks."

    return self.divs

def get_descriptions(self, check):
    "Return a list of descriptions."
if check == 1:
    self.descriptions.pop(0)
    return self.descriptions

2 个回答

1

我不太确定你的代码在做什么,但我猜你可能想用 == 而不是 is。使用 is 是在比较对象的身份,也就是说它检查的是两个对象是否是同一个,而这和字符串的相等性是 不一样 的。两个不同的字符串对象可能包含相同的字符序列。

result = oldUser[0] == oldUser[1]

如果你感兴趣,想了解更多关于 is 操作符的行为,可以查看这个链接:Python “is” 操作符在处理整数时表现得很意外

5

不要用 is 来比较字符串。这是检查它们是否是同一个对象,而不是检查两个字符串的内容是否相同。举个例子:

>>> string = raw_input()
hello
>>> string is 'hello'
False
>>> string == 'hello'
True

另外,myparser 的定义也会很有帮助。

撰写回答