I know that in Python this is possible:
'\n'.join(alist)
Assuming the 'alist' is a list of urls, can I output an HTML string which will produce a list of href tags, something like this
'<a href="'.join(alist)
I know the above is wrong, but I was wondering if there was a smarter way to do this. I have done the following with works:
fo开发者_StackOverflow社区r u in adict[alist]:
fileHandle.write('<a href="' + u + '">' + u + '</a><br>')
Basically, is there a way of somehow replacing the above for loop with a join statement? A one-liner perhaps?
You're looking for a generator expression:
''.join('<a href="' + u + '">' + u + '</a><br/>' for u in adict[alist])
If you don't want a <br/>
after the last item, move the <br/>
into the string to join with.
Also, I'm assuming here adict[alist]
contains HTML code. If it contains text, you must wrap u
with html.escape()
(replacing <
with <
and "
with "
). Otherwise, you're introducing a Cross-Site scripting vulnerability (and rendering bugs).
Yes
fileHandler.write('<br/>\n'.join('<a href="%(url)s">%(url)s</a>' % {'url':u} for u in adict[alist])
EDITED: modified to use write method and join results using newline and '
' tag
How about the following?
['<a href="{0}">{0}</a><br>'.format(u) for u in alist]
Update:
fileHandler.write('<br />\n'.join('<a href="{0}">{0}</a>'.format(u) for u in alist)
精彩评论