Spaces from string specifier

Ian Clark iclark at mail.ewu.edu
Fri Sep 14 18:50:44 EDT 2007


Gabriel Genellina wrote:
> En Fri, 14 Sep 2007 01:57:43 -0300, Gavin Tomlins <gavin at madzag.com>  
> escribi�:
> 
>> I'm trying to work out when using a format specifier I get spaces in the
>> resulting string.  Eg. Looking at the outputted string you can see that
>> there are spaces after T5LAT, F4LAT etc. as I result from trying to keep  
>> the
>> code aligned
> 
> - You should *not* build the SQL text yourself; use a parametrised query  
> instead. It's not only easier to write; it's safer, less error prone, and  
> maybe faster. See this previous post  
> <http://groups.google.com/group/comp.lang.python/browse_thread/thread/b8c1ef8471f55995/>
> 
> - Spaces are not significant in SQL, but you may have your own reasons to  
> format the SQL text in a certain way. In addition to the ideas already  
> menctioned on that thread (avoid \, use parenthesis, and auto-concatenate  
> adjacent strings), you may use a triple-quoted string + function dedent  
>  from textwrap module:
> 
> py> fmtSqlP300Amp = textwrap.dedent('''\
> ...           UPDATE Patient SET
> ...             O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s",
> ...             P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s",
> ...             TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s"
> ...           WHERE Pat_Id = "%s"''')
> py> print fmtSqlP300Amp
> UPDATE Patient SET
>    O2AMP = "%s", O1AMP = "%s", OzAMP = "%s", PzAMP = "%s",
>    P4AMP = "%s", CP4AMP = "%s", T6AMP = "%s", C4AMP = "%s",
>    TP8AMP = "%s", T4AMP = "%s", T5AMP = "%s", P3AMP = "%s"
> WHERE Pat_Id = "%s"
> 
> I hope any of these ideas will fit your own needs.

Completely agree that this should not be written by hand. But if you 
absolutely *must* you might try something like this:

     >>> fmt = """
     ...     UPDATE Patient SET
     ...     02AMP = "%(o2amp)s"
     ...     O1AMP = "%(o1amp)s"
     ...     ...
     ... """
     >>> args = {
     ...     'o1amp': "2.77413",
     ...     'o2amp': "2.43119"
     ... }
     >>> print fmt % args

             UPDATE Patient SET
             02AMP = "2.43119"
             O1AMP = "2.77413"
             ...

     >>>

Ian




More information about the Python-list mailing list