简体   繁体   中英

python: how to print separate lines from a list?

This is my code:

class Message:

    def __init__(self,sender,recipient):
        self.sender = sender
        self.recipient = recipient
        self.wishList = []

    def append(self,line):
        self.wishList.append(str(line))
        for i in line:
            return i

    def toString(self):
        return 'From:{}\nTo:{}\n{}'.format(self.sender,self.recipient,
                                           self.wishList)

and the output is:

From:Aria

To:Santa

['For Christmas, I would like:', 'Video games', 'World peace']

How can I separate the lines and make the output as following?

From:Aria

To:Santa

For Christmas, I would like:

Video games

World peace

You can convert list to string by "joinerchar".join(list) . In your code it will be like this.

return 'From:{}\nTo:{}\n{}'.format(self.sender,self.recipient,
                                       "\n".join(self.wishList))

Imagine your array is arr

Then do "\\n".join(arr) it basically takes the array and inserts a new line between each one.

With that example, you should be able to figure it out :) Comment if you need more help.

First, some observations:

  1. why are you returning the first character after adding an element to your wishList? (I consider it useless, so I have removed it from my answer)

  2. I think you should add For Christmas, I would like: as part of your template to print.

  3. using str.join() is probably the best alternative to concatenate the elements of the wishList.

  4. Have you ever heard of PEP-8 , basically it seems that you come from a language as Java or C# since you are using upperCamelCase, in Python _ is preferred.

  5. I don't think that converting line to str is relevant assuming you are going to enter a string, but let's leave it.

Assuming you are using Python 3.6+, you can use string interpolation:

class Message:
    def __init__(self, sender, recipient):
        self.sender = sender
        self.recipient = recipient
        self.wish_list = []

    def append(self, line):
        self.wish_list.append(str(line))

    def toString(self):
        nl = '\n'
        return f'From: {self.sender}{nl}To: {self.recipient}{nl}For Christmas, I would like:{nl}{nl.join(self.wish_list)}'

If you run the following code:

m = Message('Aria', 'Santa')
m.append('Video games')
m.append('World peace')
print(m.toString())

The output will be:

From: Aria
To: Santa
For Christmas, I would like:
Video games
World peace

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