Skip to content Skip to sidebar Skip to footer

How Do I Add A String And An Int Object In Python?

What do I need? I have SQL content like: ('a', 1), So I do: return_string = '(' for column in columns: return_string += ''' + column + '', ' return_string = return

Solution 1:

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

Solution 2:

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

return_string = "(" +', '.join((repr(column) forcolumnin 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.

Solution 3:

You can create a function to represent your type correctly:

deftoStr(x):
    ifisinstance(x, int):
        returnstr(x)
    #another elif for others typeselse:
        return"'"+x+"'"

And use

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

to print in the correct format.

Post a Comment for "How Do I Add A String And An Int Object In Python?"