Search code examples
pythonstringlistrepr

Using __str__ to return a variable number of different lined strings?


I'm working on a project that creates "Facebook" in Python 3.x. The part I am currently stuck on is using the str function to return strings on different lines.

The code I am using for this is:

class Status:
    likers = []
    commentObjs = []
    def __init__(self, statusPoster, statusMsg, likers, commentObjs):
        self.statuser = statusPoster
        self.status = statusMsg
        self.likers = likers
        self.commentObjs = commentObjs

and

def __str__(self):
    return '%s: %s \n"hello"' %(self.statuser,self.status)

__repr__= __str__

The problem that I am running into is that there can be a variable number of likers and a variable number of commentObjs.

What would I have to implement to make it so if there is only one value such as:

likers = ["Spongebob"] 
commentObjs = ["Spongebob: You should watch the Spongebob movie!"]

It returns in the terminal:

Brad Pitt will watch a movie today!
Spongebob likes this.
Spongebob: You should watch The Spongebob movie!

But if there is more than one value in each list, such as:

likers = ["Spongebob","Harry Potter"] 
commentObjs = ["Spongebob: You should watch the Spongebob movie!","Brad Pitt: How about nah?"]

It returns:

Brad Pitt will watch a movie today!
Spongebob, Harry Potter likes this.
Spongebob: You should watch The Spongebob movie!
Brad Pitt: Nah, I will probably watch Mr and Mrs. Smith.

The only way I could think to possibly do this would be something with a for loop and len(likers), but I don't know how I would be able to do that while still returning the constant values of the name and status.


Solution

  • You are looking for str.join() here. This lets you join several strings with a joining string between (which can be empty):

    >>> likers = ['Spongebob', 'Harry Potter']
    >>> ', '.join(likers)
    'Spongebob, Harry Potter'
    >>> ' -> '.join(likers)
    'Spongebob -> Harry Potter'
    

    You probably also want to learn about str.format() to interpolate values into a template string:

    def __str__(self):
        likers = ', '.join(self.likers)
        comments = '\n'.join(self.commentObjs)
        return '{} {}\n{} likes this.\n{}'.format(
            self.statuser, self.status, likers, comments)
    

    This joins your likers value with commas, and the comments with newlines.

    You should not use this as your __repr__; that should produce debugging output, helping you distinguish between two instances of your class, optionally with the contained values part of that output.