简体   繁体   中英

In python, how to use __str__ to return elements in a list, line by line

I have a class Numberlist which takes a list of numbers.

class Numberlist:
    def __init__(self,number):
        self.number=number
    def __str__(self):
        for i in self.number:
            print(i)
        return '{}'.format('')

I want to display the list of numbers in the following format when printing a object.

x = Numberlist([1,2,3,4,5,6])
print(x)
print("done printing")
1 
2 
3
4
5
6

done printing

My attempt is not correct because there is an empty line at the end of the output. I am stuck because __str__ requires you to return string type element.

What you're seeing

You're seeing an extra newline because you're printing every element in the list in your __str__ function then printing the value returned from __str__ : namely, "" . Unless you designate end in print , it defaults to a newline, so you're effectively printing "\\n" .

What you (probably) want to do

You probably want to print just the stringified representation of your class. If that's each element newline-delimited, I'd define __str__ in the following way:

def __str__(self):
    return '\n'.join(map(str, self.number))

This will put a newline between the string representation of each element in self.number and return that single string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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