Reputation: 92099
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_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 an int into a string, everything works and I get:
('a', '1'),
But I need
('a', 1),
where 1 is unquoted '
Upvotes: 1
Views: 1199
Reputation: 1
class StrInt:
def __init__(self, strin, inte):
self.strin = strin
self.inte = inte
def add(self, a, b):
self.strin = a
self.inte = b
wordNum = f"{a} {b}"
print(wordNum)
strInt = StrInt("Word", 2)
strInt.add(120, "cars")
print(type(strInt)
How many word are we talking about. I came up class which adds a word and a number using f". The function in the class adds a word and and integer.
Upvotes: -1
Reputation: 68
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 the correct format.
Upvotes: 1
Reputation: 23251
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) 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.
Upvotes: 1
Reputation:
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)"
Upvotes: 7