forced spaces when inserting a variable between strings
Xavier Morel
xavier.morel at masklinn.net
Tue Jan 17 11:18:15 EST 2006
mjteigen wrote:
> I'm very new at Python, but have been trying it in conjunction with
> CGI. I've encountered a problem that I'm pretty sure is a trivial one,
> but I don't know enough Python to work it out. Here's an example.
> Imagine that I have a file named "5.jpg" in the same directory as this
> Python script:
>
> print "content-type: text/html\n"
> number = 5
> print "<img src=",number,".jpg>"
>
> My goal is print out '<img src="5.jpg">'. However, when I view the
> source on the generated html page, I see this:
>
> <img src= 5 .jpg>
>
> In other words, that "5" has a space tacked on either side of it, and
> of course a browser can't find the file. Is there a way I can avoid the
> tacking of spaces on either side of a variable inserted between two
> strings?
>
> TIA :-)
> --
> m j teigen
>
1- Use sys.stdout.write(), it doesn't add any kind of formatting to the data
2- You may also use string interpolation, either in sys.stdout.write or
in print
3- I'd suggest you to use a templating system in order to separate the
displayed data and the retrieval/computations of said data, and prevent
from mixing logic and presentation in your scripts (which always leads
to an unmaintainable system)
More information about the Python-list
mailing list