dazzathedrummer
dazzathedrummer

Reputation: 531

Python: how to output a string in tabular form

I've got an array in a funcion...

for i in data:
    dates.append(str(i['month'])+": "+str(i['the_days']))

that I'm pulling into the body of an email like this...

date_list = avDates()
date_list_string = ' '.join(date_list)

html = """"<html>
<head></head>
<body>
<p> These are the dates: </p>
""" + date_list_string + """
</body>
<html>
"""

and this is returning the data as a string within the email...

Apr: 16, 29 May: 13, 27 Jun: 10, 11, 24 etc

How can I change the code so that the string is shown in tabular for or with a line break after each i ?

Apr: 16, 29 
May: 13, 27 
Jun: 10, 11, 24 
etc

I've tried putting "/n" in various places but it just prints out rather than being executed.

Upvotes: 0

Views: 87

Answers (2)

jDo
jDo

Reputation: 4010

If you're printing to terminal, "\n" means a newline. In HTML, <br> or <br/> (XHTML) is used for line breaks instead. So:

for i in data:
    dates.append(str(i['month'])+": "+str(i['the_days']) + "<br>")

# OR

for i in data:
    dates.append("{}: {}<br>".format(str(i['month']), str(i['the_days']))

# OR 

date_list_string = '<br>'.join(date_list)

Upvotes: 2

Byte Commander
Byte Commander

Reputation: 6736

Join your dates list with a newline character \n instead of a space:

date_list_string = '\n'.join(date_list)

This will create one date element per line in the string output. But as you're using this to build HTML, you (also or instead of that) need to insert HTML line-break tags:

date_list_string = '<br/>'.join(date_list)

Or with both line-breaks in the string and HTML:

date_list_string = '<br/>\n'.join(date_list)

Upvotes: 4

Related Questions