Home > database >  How to insert a new line to each element in a list in python
How to insert a new line to each element in a list in python

Time:05-12

Sample Output:

[
     '----',
     'S',
     'the friends are sitting in the little chicken cafe together after happily having submitted 
      their assignment 3. This is the most convenient spot for them and was where they worked on 
      the assignment together. Feeling their caffeine levels dropping below optimal, someone heads 
      to the counter and offers to buy everyone a coffee. Many seconds pass while waiting in line 
      (at least seven!) before they reach the front only to discover they left their wallet at 
      home. They decide to...',
     '====',
     '1. [diplomacy 5] use their diplomacy skills to request ask for a freebie -1  2',
     '2. [acumen 4] draw on all their internal acumen to *will* a coffee into existence   3  4-1',
     '3. [acrobatics 3] use their acrobatics skills to dash home and return with their wallet 
      before the other patrons are the wiser  5 -E~1',
     '4. give up and return to the table -E~1'
]

My code: with open (filename, "r") as file:

    my_list = file.read().splitlines()

My code Output:

['----','S','the friends are sitting in the little chicken cafe together after happily having submitted their assignment 3. This is the most convenient spot for them and was where they worked on the assignment together. Feeling their caffeine levels dropping below optimal, someone heads to the counter and offers to buy everyone a coffee. Many seconds pass while waiting in line (at least seven!) before they reach the front only to discover they left their wallet at home. They decide to...','====','1. [diplomacy 5] use their diplomacy skills to request ask for a freebie -1  2','2. [acumen 4] draw on all their internal acumen to *will* a coffee into existence   3  4 -1','3. [acrobatics 3] use their acrobatics skills to dash home and return with their wallet before the other patrons are the wiser  5 -E~1','4. give up and return to the table -E~1']

My question is, how can I output each element in the list with a new line before the next element.

I have tried using "\n".join() but the output doesn't have quote for each element in the list

CodePudding user response:

with open (filename, "r") as file:
    my_list = file.read().splitlines()
    my_list = list(map(lambda s: s   '\n', my_list))

Try this one.

CodePudding user response:

To get the pretty printed output you want, print the repr of each string on a separate line:

print('[')
for line in my_list:
    print(repr(line))
print(']')

You can get a similar, but more compact representation, by pretty-printing with pprint:

from pprint import pprint

pprint(my_list, indent=4)
  • Related