string.join question

Dennis Lee Bieber wlfraed at ix.netcom.com
Thu Oct 3 01:16:02 EDT 2002


andy surany fed this fish to the penguins on Wednesday 02 October 2002 
08:28 pm:

> I'm accessing MySQL from Python. This is for an insert statement which
> looks like this:
> 
> 
>    values = [input1, input2]
> # input values are derived from askstring, ex: input1 = aaa, input
> # =bbb
>    sqlcmd = sql.Insert_Cmd (tables, columns, values)
> 
-----------------------------------------------------------------------
>   def Insert_Cmd(self,tables,fields,values):
> 
>     insert_str = 'INSERT INTO %s ( %s ) VALUES ( %s )' %
> 
(string.join(tables,','),string.join(fields,','),string.join(values,','))
> 
> This yields: INSERT INTO tablename (column1,column2) VALUES (aaa,bbb)
> 
> What I need is:
> INSERT INTO tablename (column1,column2) VALUES ('aaa','bbb')
> 

>>> def squote(tuple):
...     otuple = [string.join(['',x,''],"'") for x in tuple]
...     return otuple
...
>>> a = ('123', 'abc', "cde")
>>> b = squote(a)
>>> print string.join(b,',')
'123','abc','cde'


        OR, in ~one line:

>>> insert_str = "INSERT INTO %s ( %s ) VALUES (%s)" % ("atable",
...     string.join(("c1", "c2", "c3"),","),
...     string.join([string.join(['',x,''],"'") for x in 
("val1","val2","val3")],','))
>>> print insert_str
INSERT INTO atable ( c1,c2,c3 ) VALUES ('val1','val2','val3')





--
 > ============================================================== <
 >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
 >      wulfraed at dm.net     |       Bestiaria Support Staff       <
 > ============================================================== <
 >        Bestiaria Home Page: http://www.beastie.dm.net/         <
 >            Home Page: http://www.dm.net/~wulfraed/             <



More information about the Python-list mailing list