1

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 '

0

4 Answers 4

7

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)"
Sign up to request clarification or add additional context in comments.

4 Comments

@KonradRudolph Percent is quicker to type and get an answer up. Once its in I always add format after (I can never remember some of the more interesting syntax of it).
@KonradRudolph percent is also quicker execution!
@mhlester Do you have statistics to prove this? Even so, “correct” is better than “fast but broken”, and the documentation says specifically that “… [% substitutions] are obsolete and may go away in future versions of Python”.
@KonradRudolph, yes, but hard to fit in a comment: timeit(lambda: "('%s', %d)" % ('a', 1), number=1000000) and timeit(lambda: "('{0}', {1})".format('a', 1), number=1000000) format took 35% longer. I may be mistaken but think they undepricated it for that reason.
1

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.

Comments

1

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.

Comments

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

2 Comments

Please don't stress that your answer may be wrong, it distracts from your solution. If it is wrong, then others will point it out in the comments and by voting, and you can then delete your answer if you wish.
The only thing of actual value here is f"{a} {b}", that class wrapper does nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.