

Python: how to add string and int object?


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):


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

>>> 1 + "1"

Traceback (most recent call last):




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)+")"
>>> "('"+x+"',"+str(y)+")"
>>> "("+repr(x)+","+str(y)+")"

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

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

Or the more standard and approved format mini-language:

>>> "({0},{1})".format(x,y)
>>> "('{0}',{1})".format(x,y)
>>> "({0},{1})".format(repr(x),y)

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
        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)