我正在学习 python 并尝试一个非常简单的字符串格式化行,但它无法正常工作。从下面的输出中可以看出,它在 3 个中的最后一个插入数字,但前 2 个只显示代码而不是数字。我确信解决方案很简单,但我已经尝试查看我的代码与我拥有的学习 Material 中的代码,但我看不出有任何区别。在 Visual Studio 2015 中使用 Python 3.4。
提前感谢您提供的任何帮助! :)
CODE(面积为200)
print("The area of the square would be {0:f} " .format(area))
#This is an example with multiple numbers and use of "\" outside of a string to allow for
#multiple lines of code in the same line spread out over numerous lines
print("Here are three other numbers." + \
" First number is {0:d}, second number is {1:d}, \n" + \
"third number is {2:d}" .format(7,8,9))
输出
正方形的面积为 200.000000
这是另外三个数字。第一个数字是 {0:d},第二个数字是 {1:d}, 第三个数字是 9。
线程“MainThread”(0xc10) 已退出,代码为 0 (0x0)。
程序“[4968] python.exe”已退出,代码为 -1073741510 (0xc000013a)。
最佳答案
这里的问题是,格式化方法只在 3 个相加的字符串中的最后一个字符串被调用。您应该在AFTER 连接字符串后应用格式操作,或者使用接受换行符的单一字符串格式(这样您就不必首先连接字符串)。
要在连接后应用,您可以在字符串连接周围使用一组额外的括号,例如
print(("Here are three other numbers." + \
" First number is {0:d}, second number is {1:d}, \n" + \
"third number is {2:d}") .format(7,8,9))
或者您可以使用三重引号来接受换行符,例如
print("""Here are three other numbers.\
First number is {0:d}, second number is {1:d},
third number is {2:d}""" .format(7,8,9))
其中 \
允许在不会打印的代码中换行。
关于python - 非常基本的字符串格式不起作用(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32376410/