Skip to main content
 首页 » 编程设计

python之在前面添加文本之Python

2025年05月04日12JeffreyZhao

我有下面的代码

Test1 =  Price[Product.index(TestABC)]+   AddQTYPriceA 
 
print Test1 
print "try this test" + Test1 

当它需要打印测试 1 时,它会给出正确答案。我想尝试在它的前面添加文本,所以我输入了 print "try this test"+ Test1

对于第二个打印命令,它给出了以下错误。

Traceback (most recent call last): 
  File "C:\Python26\data.py", line 78, in <module> 
    print "try this test" + Test1 
TypeError: cannot concatenate 'str' and 'float' objects 

有人可以帮助我如何让文本出现在前面。

格雷吉·D

请您参考如下方法:

为了连接字符串和 float ,您需要使用 str() 函数将 float 转换为字符串。

print "try this test " + str(Test1) 

或者您可以使用 .format() 字符串方法:

print "try this test {0}".format(Test1) 

这两种方法都记录在 python string built-in type page 上.