Skip to main content
 首页 » 编程设计

python之如何在 Python 中添加一个字符串和一个 int 对象

2025年05月04日23fff_TT

我需要什么?

我的 SQL 内容如下:

('a', 1), 

我也是这样的:

return_string = '(' 
    for column in columns: 
        return_string += "'" + column + "', " 
    return_string = return_string[:-2] + '),' 
    return return_string 

但它失败并出现同样的错误。

>>> 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 未被引号 '

请您参考如下方法:

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

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

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

或者使用字符串格式来处理幕后的一些问题。使用 (deprecated) "percent formatting" :

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

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