Python 连接字符串时插入括号
我有一个Python3程序,目前在一个部分运行得非常好。我正在计算矩形(用Python 连接字符串时插入括号,python,string,python-3.x,concatenation,Python,String,Python 3.x,Concatenation,我有一个Python3程序,目前在一个部分运行得非常好。我正在计算矩形(用graphics.py绘制)的面积和周长,并将结果连接成一个字符串。下面是我目前的代码 val = "The perimeter is" , str(2*(height + width)), " and the area is ", str(height*width) 当我使用graphics.py将其输出到页面时,结果如下所示 {The perimeter is} 215 { and the area is } 6
graphics.py
绘制)的面积和周长,并将结果连接成一个字符串。下面是我目前的代码
val = "The perimeter is" , str(2*(height + width)), " and the area is ", str(height*width)
当我使用graphics.py
将其输出到页面时,结果如下所示
{The perimeter is} 215 { and the area is } 616
我如何得到一个在文本中间没有括号的输出?即使没有
str()
,括号也存在,这不是理想的结果。理想的结果如下
周长为215,面积为616
如果我使用+
而不是,
,我会得到错误无法将'int'对象隐式转换为str
,因此这对我也不起作用
任何帮助都会很好 在python中,加号“+”可用于连接字符串
试一试
在python中,加号“+”可用于连接字符串
试一试
您的代码不会创建串联字符串
val
成为包含字符串和整数的tuple
graphics.py
似乎显示了括号,以指示每个字符串元素的开始/结束位置
Python为您这样的用例提供了字符串格式:
val = "The perimeter is {} and the area is {}".format(2*(height + width), (height*width))
有关语法的详细信息,请参阅。您的代码不会创建串联字符串
val
成为包含字符串和整数的tuple
graphics.py
似乎显示了括号,以指示每个字符串元素的开始/结束位置
Python为您这样的用例提供了字符串格式:
val = "The perimeter is {} and the area is {}".format(2*(height + width), (height*width))
有关语法的详细信息,请参见。在变量定义中使用
,
时,您创建的是元组而不是字符串。所以当你这么做的时候-
val = "The perimeter is" , str(2*(height + width)), " and the area is ", str(height*width)
val
是一个元组
,这很可能是括号的原因。我建议使用str.format
创建字符串。范例-
val = "The perimeter is {} and the area is {}".format(2*(height + width),height*width)
在变量定义中使用
,
时,创建的是元组而不是字符串。所以当你这么做的时候-
val = "The perimeter is" , str(2*(height + width)), " and the area is ", str(height*width)
val
是一个元组
,这很可能是括号的原因。我建议使用str.format
创建字符串。范例-
val = "The perimeter is {} and the area is {}".format(2*(height + width),height*width)
我认为这是一个很好的字符串格式使用案例,因为它将为您提供更大的显示结果的灵活性 例如:
val_string_2dec = 'The perimeter is {perimeter:0.2f} and the area is {area:0.2f}'
val = val_string_2dec.format(perimeter=2*(height+width), area=height*width)
print(val)
# outputs
The perimeter is 215.00 and the area is 616.00
我认为这是一个很好的字符串格式使用案例,因为它将为您提供更大的显示结果的灵活性 例如:
val_string_2dec = 'The perimeter is {perimeter:0.2f} and the area is {area:0.2f}'
val = val_string_2dec.format(perimeter=2*(height+width), area=height*width)
print(val)
# outputs
The perimeter is 215.00 and the area is 616.00
您似乎混淆了
print()
、字符串连接和tuple
s的参数。您似乎混淆了print()
、字符串连接和tuple
s的参数。如果将unicode变量与str连接,则生成的类型将是unicode,这可能会导致意外情况。使用格式
或更新的f字符串可能更安全,除非您知道类型相同,或者您正在使用的库是unicode友好的-它们都应该是unicode友好的,但现实并不总是理想的。如果您将unicode变量与str连在一起,则生成的类型将是unicode,这可能会导致意外情况。使用格式
或更新的f字符串可能更安全,除非您知道类型相同,或者您正在使用的库是unicode友好的-它们都应该是unicode友好的,但现实并不总是理想的。