Home > database >  How to print the data in 3 list on different lines
How to print the data in 3 list on different lines

Time:09-15

I have this python function and will like to print each list on a different line like this with the print(body)

        1,2,3
        4,5,6
        7,8,9

        def send_email():
            mylist1 = [1,2,3]
            mylist2 = [4,5,6]
            mylist3 = [7,8,9]

            body = ''

            for item1 in mylist1:  
                body  = str(f"{item1}")
            
            for item2 in mylist2:
                body  =  str(item2)

            for item3 in mylist3:
               body  = str(item3)


            print(body)

        send_email()
        

How can I format this?

CodePudding user response:

This should do the trick for you (assuming you want it in the same method):

mylist1 = [1,2,3]
mylist2 = [4,5,6]
mylist3 = [7,8,9]

def print_with_newline(mylist):
  body = ''
  for item in mylist:
    body  = str(item)   '\n'
  return body  

body = print_with_newline(mylist1)   print_with_newline(mylist2)   print_with_newline(mylist3)
print(body)

Let me know if this helped!

CodePudding user response:

You can use a nested str.join to assemble the contents of your lists into the body. The first (inner) join assembles the values of each list (converted to strings, so '1','2' & '3' for mylist1) with a comma between them. The second (outer) join assembles those strings into a larger string, with newlines between each string.

body = '\n'.join(','.join(str(t) for t in lst) for lst in [mylist1, mylist2, mylist3])
print(body)

Output:

1,2,3
4,5,6
7,8,9
  • Related