简体   繁体   中英

One-liner possible?

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:

for 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 &lt; and " with &quot; ). 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)

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