简体   繁体   中英

Python format output

I am a python novice. I have a bunch of sets which are included in the list 'allsets'. In each set, I have multiple string elements. I need to print all of my sets in a text file, however, I would like to find a way to separate each element with a '|' and print the name of the set at the beginning. Eg:

s1= [string1, string2...]
s2= [string3, string4...]
allsets= [s1,s2,s3...]

My ideal output in a text file should be:

s1|string1|string2
s2|string3|string4

This is the code I've written so far but it returns only a single (wrong) line:

for s in allsets:
   for item in s:
     file_out.write("%s" % item)

Any help? Thanks!

Those are not "sets", in Python, they're just lists.

The names of the variables ( s1 and so on) are not easily available programmatically, since Python variables are ... weird. Note that you can have the same object given multiple names, so it's not obvious that there is a single name.

You can go around this by using a dictionary:

allsets = { "s1": s1, "s2": s2, ...}

for k in allsets.keys():
  file_out.write("%s|%s" % (k, "|".join(allsets[k]))
for s in allsets:
   for item in s:
     file_out.write("%s|" % item)
   file_out.write("\n")

\\n changes the line.

Have a look at the CSV module. IT does everything for you

Here's an example from the documentation

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

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