views:

191

answers:

4

I know it's a really simple question, but I have no idea how to google it.

how can I do

print '<a href="%s">%s</a>' % (my_url)

So that my_url is used twice? I assume I have to "name" the %s and then use a dict in the params, but I'm not sure of the proper syntax?


just FYI, I'm aware I can just use my_url twice in the params, but that's not the point :)

+11  A: 
print '<a href="%(url)s">%(url)s</a>' % {'url': my_url}
Ignacio Vazquez-Abrams
+2  A: 

For building HTML pages, you want to use a templating engine, not simple string interpolation.

Mike Graham
I'm using Django, but this is going into an email.
Mark
Django's templating engine may also prove to be the ideal tool for the emails you are making.
Mike Graham
What's stopping you from using a Django template to generate an email body with its `render()` method? Nothing says you have to feed template output to `HttpResponse()`. Django is *embarrassingly* versatile.
Mike DeSimone
@Mike: I *thought* Django might have a solution for this too, but I hadn't found it yet :p I probably will move my emails into templates then! Thanks. Maybe I'm 'tarded, but I've found it to be pretty rigid in some areas.
Mark
@random people that read these comments: found more detail on how to do that here http://www.rossp.org/blog/2006/jul/11/sending-e-mails-templates/
Mark
+3  A: 

As well as the dictionary way, it may be useful to know the following format:

print '<a href="%s">%s</a>' % (my_url, my_url)

Here it's a tad redundant, and the dictionary way is certainly less error prone when modifying the code, but it's still possible to use tuples for multiple insertions. The first %s is substituted for the first element in the tuple, the second %s is substituted for the second element in the tuple, and so on for each element in the tuple.

Wallacoloo
I just told a guy off for suggesting this :) He deleting his post. I feel kind of bad now. Yes, I'm aware I can do this, but it just wasn't what I was looking for. As you said, it's redundant, and `my_url` is actually a function call that I don't want to have to be evaluated twice. Twice isn't so bad, but it could just have easily been 20 times :)
Mark
I figured I'd keep mine, just in case it helps somebody else. Well the dictionary way is likely the best way to go. But for redundancy, `(get_my_url(), )*20` only calls the function once, and duplicates it 20 times.
Wallacoloo
woah...that's crazy/neat.
Mark
+2  A: 

In Python 3, you might choose to use the new string formatting method.

print('<a href="{0}">{0}</a>'.format(my_url))
Greg Ball
This also works for Python 2.6.
Scott Griffiths
My server uses Python 2.5 :(
Mark