嗨,我正在努力使用非常基本的 python 代码。我遇到一个错误说类型错误:只能将str(而不是"int")连接到str


class Yookyung:
def __init__(self, feeling, weight):
self.feeling = feeling
self.weight = weight

def speak(self):
print("Iam so "+ self.feeling+ "because I am"+ self.weight+ "kg now.")
SadYookyung = Yookyung("sad", 57)
SadYookyung.speak()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-2639abd46a5d> in <module>
----> 1 SadYookyung.speak()
<ipython-input-1-a640ca3e899e> in speak(self)
5 
6     def speak(self):
----> 7         print("Iam so "+ self.feeling+ "because I am"+ self.weight+ "kg now.")
TypeError: can only concatenate str (not "int") to str

一种简单的方法,

def speak(self):
print(f"Iam so {self.feeling} because I am {self.weight}kg now.")

注意:请确保使用python的最新版本,因为在某些更低的版本中版本不支持这种格式。

尝试f字符串:

def speak(self):
print(f"I am so {self.feeling} because I am {self.weight} kg now.")

之所以会发生这种情况,是因为在两个字符串之间使用+意味着串联,在两个数字之间使用意味着求和,所以当混合这些类型时,解释器会感到困惑。

Python提供了一种非常简单的方法来格式化字符串,因此您不必担心数据类型和连接:

name = 'Guest'
greet = 'Hello'
print(f'{greet} {name}')
# or
print('{} {}'.format(greet, name))

最新更新