string - python 如何连接str和int对象?

如果我尝试执行以下操作:


things = 5


print("You have" + things +" things.")



在python 3.x中出现以下错误:


Traceback (most recent call last):


 File"<stdin>", line 1, in <module>


TypeError: must be str, not int



在python 2.x中出现类似的错误:


Traceback (most recent call last):


 File"<stdin>", line 1, in <module>


TypeError: cannot concatenate 'str' and 'int' objects



我该如何解决这个问题?

时间:

在这里,+运算符在中有两个不同的含义: 对于数值类型,它意味着"将数字相加":


>>> 1 + 2


3


>>> 3.4 + 5.6


9.0



对于序列类型,它意味着"连接序列":


>>> [1, 2, 3] + [4, 5, 6]


[1, 2, 3, 4, 5, 6]


>>> 'abc' + 'def'


'abcdef'



通常,python不会为了使操作有意义而将对象从一种类型隐式转换为另一种类型,因为这会造成混淆: 例如,你可能认为'3' 5应该表示'35',但是别人可能认为它应该意味着8甚至'8' 。

同样,python不会让你连接两种不同类型的序列:


>>> [7, 8, 9] + 'ghi'


Traceback (most recent call last):


 File"<stdin>", line 1, in <module>


TypeError: can only concatenate list (not"str") to list



因此,你需要显式地执行转换,无论你想要连接还是相加:


>>> 'Total: ' + str(123)


'Total: 123'


>>> int('456') + 789


1245



但是有一个更好的方法,


>>> things = 5




>>> 'You have %d things.' % things # % interpolation


'You have 5 things.'




>>> 'You have {} things.'.format(things) # str.format()


'You have 5 things.'




>>> f'You have {things} things.' # f-string (since Python 3.6)


'You have 5 things.'



也允许你控制如何显示值:


>>> value = 5


>>> sq_root = value ** 0.5


>>> sq_root


2.23606797749979




>>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)


'The square root of 5 is 2.24 (roughly).'




>>> 'The square root of {v} is {sr:.2f} (roughly).'.format(v=value, sr=sq_root)


'The square root of 5 is 2.24 (roughly).'




>>> f'The square root of {value} is {sq_root:.2f} (roughly).'


'The square root of 5 is 2.24 (roughly).'




>>> things = 5


>>> print('you have', things, 'things.')


you have 5 things.


>>> print('you have', things, 'things.', sep=' ... ')


you have ... 5 ... things.



但这不如使用Python的字符串格式化功能灵活。


>>> 1 + 2.3


3.3


>>> 4.5 + (5.6+7j)


(10.1+7j)



磅;DR博士

其中之一: print("You have" + str(things) +" things.") ( 旧的学校)

或者: print("You have {} things.".format(things)) ( 新 Pythonic 和推荐的方式)

的语言解释一下:
尽管上面的优秀 @Zero Piraeus回答没有涵盖,但是我将尝试对它进行"缩小":
由于those运算符与 each/number运算符的定义不同,因此不能在 python 中连接字符串和数字( 任何种类的) 。 因此,为了在对象之间解决这个"误解":

Have fun read阅读Piraeus答案,当然值得你时间

只需运行下面的代码即可:


def myprint(*arg): 


 strToPrint =""


 for item in arg:


 strToPrint += str(item)


 print(strToPrint)


def concatByComma(*arg):


 strToPrint =""


 for item in arg:


 strToPrint += str(item)


 return strToPrint


I ="I"; i=5


print(I," am" , i ," years old")


print(('s','o', I),[' wrote','it:'],' ',{1:'hour'},'and',5," min.")


myprint(('s','o', I),[' wrote','it:'],' ',{1:'hour'},'and',5," min.")




things = 5


print("You have" + str(things) +" things.")



两者都适用于python 2python 3

...