如何在同一行代码中使用字符串 (str) 和整数 (int)?

How do I use a string (str) and an integer (int) in the same line of code?

每当我尝试 运行 这段代码时,我都会收到关于 str()int() 的错误:

current_year = input ("What year is it?")

current_year = int(current_year)

birth_year = input ("What year were you born in?")

birth_year = int(birth_year)

print ("You are") + (current_year - birth_year) + ("years old.")

我怎样才能让这段代码起作用?

如有任何帮助,我们将不胜感激!

将 str(number) 添加到您的打印语句中。

print ("You are " + str(current_year - birth_year) + " years old.")

尝试 使用 python 的内置 str() 方法将整数转换为字符串,然后只需添加适当的字符串连接,如下所示:

 print("You are " + str(current_year  -  birth_year) + " years old.")

希望对您有所帮助!

尼克,我看到你是 11 岁的参赛者 - 保持热情,来这里寻求答案,但先做你的 HW。

字符串 str() 基本上是长文本。所以如果你想和其他文本拼接(join back to back),你必须先把数字转换成文本。因此 str (1972 -1960) 会给你 12 作为文本字符串。一旦它处于那种形式,对它的数学运算将 return 一个错误或 null,但是 str(current_year - birth_year) + "岁。"会给你“12岁”。 - 考虑了 'space'。