连接字符串时的括号注入

Bracket Injection when Concatenating String

我有一个 python 3 程序,目前它的一个部分运行得非常好。我正在计算一个矩形(用 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(),括号也存在,这不是理想的结果。理想的结果如下。

The perimeter is 215 and the area is 616

如果我使用 + 而不是 ,,我会得到错误 Can't convert 'int' object to str implicitly,所以这对我也不起作用。

任何帮助都会很棒!

在python中,加号“+”可用于连接字符串。

尝试

val = "The perimeter is " + str(2*(height + width)) + " and the area is " + str(height*width)

您的代码没有创建串联字符串。 val 变成包含字符串和整数的 tuplegraphics.py 似乎显示括号以指示每个字符串元素 begins/ends.

Python 具有适用于像您这样的用例的字符串格式:

val = "The perimeter is {} and the area is {}".format(2*(height + width), (height*width))

有关语法的详细信息,请参阅 https://docs.python.org/3.1/library/string.html#format-string-syntax

当您在变量定义中使用 , 时,您创建的是元组而非字符串。因此当你做 -

val = "The perimeter is" , str(2*(height + width)), " and the area is   ", str(height*width)

valtuple ,这很可能是括号的原因。我建议使用 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

For a full list of formatting options, head over to the official documentation