TypeError:序列项0:预期的str实例,找到int

时间:2014-12-22 21:10:22

标签: python

def stringToLek(red):
    lek = {}
    deo = red.strip().split("|")
    lek["ser_br"] = int(deo[0])
    lek["fab_naziv"] = deo[1]
    lek["gen_naziv"] = deo[2]
    lek["kol_leka"] = int(deo[3])
    lek["c_leka"] = float(deo[4])
    return lek
def  lekToString(lek):
    return '|'.join([lek['ser_br'], lek['fab_naziv'], lek['gen_naziv'], lek['c_leka'], lek['kol_leka']])

............................................... ..................................

TypeError: sequence item 0: expected str instance, int found

3 个答案:

答案 0 :(得分:3)

join()的所有参数都必须是字符串。它会在你的第一个lek['ser_br']窒息,因为它不是字符串,而是intlek["kol_leka"]lek["c_leka"]会遇到同样的问题。

答案 1 :(得分:2)

def  lekToString(lek):
return '|'.join([str(lek['ser_br']), str(lek['fab_naziv']), str(lek['gen_naziv']), str(lek['c_leka']), str(lek['kol_leka'])])

答案 2 :(得分:1)

也许您应该定义一个类来实现此行为?

class Lek:
    def __init__(self, red):
        deo = red.strip().split("|")
        self.ser_br = int(deo[0])
        self.fab_naziv = deo[1]
        self.gen_naziv = deo[2]
        self.kol_leka = int(deo[3])
        self.c_leka = float(deo[4])
        return self

    def __str__(self):
        # The order here is different than in the initializer, I guess it's a bug?
        return '|'.join([
            self.ser_br, self.fab_naziv, self.gen_naziv, self.c_leka, self.kol_leka])


def stringToLek(red):
    return Lek(red)

def  lekToString(lek):
    return str(lek)

课外的def在这一点上毫无用处,但我留给他们只是为了向您展示它们的外观。

这可能不是解决问题的理想方法,但是至少显示了一种重构,该重构使用面向对象的编程将逻辑封装在类中。刚开始时,强制其余代码只使用类的方法与之交互就像拖拉一样,但是通过减少代码不同部分之间的内部耦合,这极大地帮助了工作。

您还可以通过使lekstr的子类来解决此问题。但是,这存在挑战。参见例如https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/(它讨论的是dict,而不是str,但问题相似)。实际上,如果您小心一点,可以从str继承,但是必须重写__new__而不是__init__

class Lek(str):
    def __new__(cls, seq):
        self = super().__new__(cls, seq)
        deo = seq.strip().split("|")
        self.ser_br = int(deo[0])
        self.fab_naziv = deo[1]
        self.gen_naziv = deo[2]
        self.kol_leka = int(deo[3])
        self.c_leka = float(deo[4])
        return self