问题描述:

What I need?

A sql like

('a', 1),

so I do

return_string = '('

for column in columns:

return_string += "'" + column + "', "

return_string = return_string[:-2] + '),'

return return_string

but it fails with the same error

>>> a = 'a'

>>> a + 1

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: cannot concatenate 'str' and 'int' objects

>>> 1 + "1"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>>

However, if I convert int into string, everything works and I get

('a', '1'),

but I need

('a', 1),

where 1 is unquoted '

网友答案:

String concatenation in python only works between strings, it doesn't infer types based on need like other languages.

There are two options, cast the integer to a strings and add it all together:

>>> x ="a"
>>> y = 1
>>> "("+x+","+str(y)+")"
'(a,1)'
>>> "('"+x+"',"+str(y)+")"
"('a',1)"
>>> "("+repr(x)+","+str(y)+")"
"('a',1)"

Or use string formatting to take care of some of this behind the scenes. Either using (deprecated) "percent formatting":

>>> "(%s,%d)"%(x,y)
'(a,1)'
>>> "('%s',%d)"%(x,y)
"('a',1)"
>>> "(%s,%d)"%(repr(x),y)
"('a',1)"

Or the more standard and approved format mini-language:

>>> "({0},{1})".format(x,y)
'(a,1)'
>>> "('{0}',{1})".format(x,y)
"('a',1)"
>>> "({0},{1})".format(repr(x),y)
"('a',1)"
网友答案:

It finally clicked what you want and what your input is! It's for arbitrary length columns object! Here ya go:

return_string = "(" + ', '.join((repr(column) for column in columns)) + ")"

Output is exactly as requested:

('a', 1)

All previous answers (including my deleted one), were assuming a fixed two-item input. But reading your code (and wading through the indent corruption), I see you want any columns object to be represented

网友答案:

you can create a function to represent your type correctly

def toStr(x):
    if isinstance(x, int):
        return str(x)
    #another elif for others types
    else:
        return "'"+x+"'"

and use

myTuple = ('a', 1, 2, 5)
print "("+", ".join(toStr(x) for x in myTuple)+")"

to print in correct format

网友答案:

You cant concatenate (or join) integers with strings. Also repeated string concatenations like that are really slow. repr will put quots around strings but not integers, while turning them both into strings. Try this:

return  "(%s)," % ", ".join(repr(c) for c in columns)
相关阅读:
Top