如何在Python中添加字符串和int对象?

2024-04-30 05:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要什么?

我的SQL内容如下:

('a', 1),

所以我要:

^{pr2}$

但同样的错误也失败了。在

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

但是,如果我把一个int转换成一个字符串,一切正常,我得到:

('a', '1'),

但我需要

('a', 1),

其中1是不带引号的'


Tags: andinmostsqlstdinlinecallfile
3条回答

它最终点击了你想要的和你输入的内容!它是针对任意长度的列对象!给你:

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

输出完全符合要求:

^{pr2}$

之前所有的答案(包括我删除的一个)都假设输入了固定的两个条目。但是,阅读代码(并处理缩进损坏),我发现您希望表示任何columns对象。在

您可以创建一个函数来正确表示您的类型:

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

和使用

^{pr2}$

以正确的格式打印。在

Python中的字符串连接只在字符串之间起作用。它不像其他语言那样根据需要推断类型。在

有两个选项,将整数转换为字符串并将其全部相加:

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

或者使用字符串格式在幕后处理这些问题。使用(deprecated) "percent formatting"

^{pr2}$

或者更多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)"

相关问题 更多 >