Busko
Busko

Reputation: 39

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

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

Upvotes: 2

Views: 13720

Answers (3)

tripleee
tripleee

Reputation: 189679

Perhaps instead you should define a class to implement this behavior?

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)

The defs outside the class are pretty useless at this point, but I left them in just to show you what they would look like.

This may not be the ideal solution to your problem, but at least shows one refactoring which uses object-oriented programming to encapsulate the logic inside a class. Forcing the rest of your code to only use the methods of the class to interact with it feels like a drag when you first start, but it helps tremendously down the line by reducing the internal coupling between different parts of your code.

You could also solve this by having lek be a subclass of str. There are challenges with that, though. See e.g. https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/ (it discusses dict rather than str, but the issues are similar). In practice, if you are careful, you can inherit from str but you'll have to override __new__ instead of __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

Upvotes: 1

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'])])

Upvotes: 3

jez
jez

Reputation: 15359

All the arguments to join() must be strings. It chokes at your first one, lek['ser_br'] because that is not a string, but rather an int. lek["kol_leka"] and lek["c_leka"] will have the same problem.

Upvotes: 4

Related Questions