如何在python的打印函数中打印结果和其他单词?

如何在python的打印函数中打印结果和其他单词?,python,Python,我是python的新手,也是编程的初学者。如果我的问题低于低水平,请原谅我。我曾经在C编程中打印结果和结果旁边的其他句子,但在python中我不能这样做。我的错误截图提供了以下问题: 只能将字符串添加到字符串中。这就是python解释器所抱怨的 老办法: print("Weight in pound is: %d" %weight_lbs) print("Weight in pound is: {}".format(%weight_lbs)) 您可以改为使用f字符串: print(f"Wei

我是python的新手,也是编程的初学者。如果我的问题低于低水平,请原谅我。我曾经在C编程中打印结果和结果旁边的其他句子,但在python中我不能这样做。我的错误截图提供了以下问题:


只能将字符串添加到字符串中。这就是python解释器所抱怨的

老办法:

print("Weight in pound is: %d" %weight_lbs)

print("Weight in pound is: {}".format(%weight_lbs))
您可以改为使用f字符串:

print(f"Weight in pound is: {weight_lbs}")

有关f字符串(格式化字符串)的更多详细信息,请参阅中的第7.1.1节。

不能将字符串和浮点值合并。您需要在python3中强制转换字符串或使用f字符串

weight_kg = input('Enter your weight(in kgms): ')
weight_lbs = int(weight_kg) * 2.20462
print('Weight in pounds is' + str(weight_lbs)) # cast to str
print(f'Weight in pounds is {weight_lbs}') # f-strings format in python3

最简单、最现代的方法就是使用f字符串

例如,
print(f'Weight in pound是{Weight\u lbs})。


有关详细信息,请参阅。

另一种解决方案是使用类似于C中的占位符。
代码如下所示:

print("Weight in pound is: {}".format(weight_lbs)) 
{}
指示您要在此位置输入文本。

.format(…)
正在“自动转换”所需的输入为字符串。

请将代码和错误消息作为文本而不是文本共享screenshot@Mureinik谢谢你提供的信息,因为我是编程的初学者,也是stackoverflow的初学者!仅供参考-在您的第一个解决方案中,格式说明符应该是
%f
而不是
%d
,否则它将只打印整数值并丢弃十进制数。不知道该变量是浮点,谢谢。感谢这两个解决方案。