python string, best way to concat
Dan Stromberg
drsalists at gmail.com
Wed Aug 27 18:30:45 EDT 2014
On Wed, Aug 27, 2014 at 1:31 PM, <dennisearlevans at gmail.com> wrote:
>
> Hi,
>
> Sorry about the simple question but I am very new to Python.
>
> Anyway, I have a function that will be used to call a stored procedure and I need to format the string with the correct number of parameter markers for the ODBC driver, fairly standard stuff.
>
> What I have works but looks ugly, is there a better way to build or concatenate a string or is a list or a tuple a better option?
>
> the function looks like this
>
> def callSp(self, schema, spName) :
> sqlCode = "{call " + schema + "." + spName + "("
> par_Markers = ""
> y = len(self.param)
> x = 0
> while x < y :
> par_Markers = par_Markers.join("?")
> if (x < y - 1) :
> par_Markers = par_Markers.join(", ")
> x += 1
> self.cmdText = sqlCode + par_Markers + ")}"
> self.ExecuteCursor()
>
> return
>
> self.param is a list of parameters. sself.cmdText is the text that will be used to call the stored procedure.
>
> the function would be called like this
>
> class.AddParameter(some value 1)
> class.AddParameter(some value 2)
> callSp("schemaName", "storedProcedureName")
>
> the self.cmdText will look like this just before the ExecuteCursor call
>
> "{call schemaName.StoredProcedureName(?, ?)}"
>
> the code works, but as I said is a bit ugly, is there better methods?
>
> thanks
>
> Dennis
If you have a constant number of things to put in a string, often 'abc
{} ghi {}'.format('def', 'jkl') is good - this will produce 'abc def
ghi jkl'.
If you have a variable number of things to put in a string, toss them
all in a list, and join them:
list_ = ['abc, 'def', 'ghi']
for number in range(4):
list_.append(str(number))
list_.extend(['jkl', 'mno')
# elements of the list will be separated by one space:
string = ' '.join(list_)
More information about the Python-list
mailing list