Send formatted list of tuples as body of an email

时间秒杀一切 提交于 2019-12-08 05:28:29

问题


Maybe this has been asked already, but I can't find it, and I need help. I have a list of tuple pairs:

mylist = [('name1', 'name2'), ('name3', 'name4'), ('name5','name6')]

The list is generated from a MySQL database and can be of any length. It is possible that some of the names are the same. It is not absolutely necessary that the data type be a list of tuples. That's just what made the most sense to me. It can be a list of lists, tuple of tuples, etc. A dictionary doesn't make sense to me, because, as previously stated, any of the names can be the same. This is in python using django, which can't be changed.

Anyway, I want to send an email with the contents of Mylist as the body. I want to format it, though, so that it looks in the body of the email like this:

name1, name2
name3, name4
name5, name6

In other words, I want it to look like normal text you would see in an email body. Initially, my thinking was that I had to use a function and generate a variable for each line of output. There may be a way to get this done without creating new variables for each newline, but I can't figure it out. To be honest, I haven't figured it out at all. I've tried for loops, while loops, recursive functions, etc. No luck.

This is for work, and I could really use some help. Thanks


回答1:


The most Pythonic way that comes to mind would be:

body = '\n'.join('%s, %s' % pair for pair in mylist)


来源:https://stackoverflow.com/questions/19061490/send-formatted-list-of-tuples-as-body-of-an-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!