Finn Eggers
Finn Eggers

Reputation: 945

Python: use generators to print 2d array

I am new in python and I wanted to create a 2D array and print that one later.

self.values = [[0 for k in range(8)] for i in range(8)]

I've overwritten the __str__(self) method:

def __str__(self):
    s = (x.__str__() + "\n" for x in self.values).__str__()
    return s

def __repr__(self):
    return self.__str__()

The question is about the line, where i create the variable s.

I've tried a few things:

s = (x.__str__() + "\n" for x in self.values).__str__()

s = str((x + "\n" for x in self.values))

s = list((x.__str__() + "\n" for x in self.values))

In each case, I understand why it does not work but I can't find a way how this could work.

I am very happy if someone could show a way to use generators to create the string.

Greetings, Finn

Upvotes: 0

Views: 201

Answers (1)

Thom Wiggers
Thom Wiggers

Reputation: 7052

You're obtaining a generator that will create a list that looks somewhat like ["1\n", "2\n"]. You probably want to join that list:

''.join(s)

As join allows you to specify the joining string, you can leave out the + "\n" from the generator as well and do:

return '\n'.join(str(x) for x in self.values)

See also https://docs.python.org/3.7/library/stdtypes.html?highlight=join#str.join

Upvotes: 1

Related Questions