Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
非常基本的字符串格式设置不起作用(Python)_Python_Python 3.x_String Formatting - Fatal编程技术网

非常基本的字符串格式设置不起作用(Python)

非常基本的字符串格式设置不起作用(Python),python,python-3.x,string-formatting,Python,Python 3.x,String Formatting,我只是在学习python并尝试一个非常简单的字符串格式行,但它不能正常工作。从下面的输出可以看出,它将数字插入3的最后一个,但前2个只是显示代码而不是数字。我确信解决方案很简单,但我试着看一下我的代码和学习材料中的代码,我看不出有什么区别。在Visual Studio 2015中使用Python 3.4 提前感谢您提供的任何帮助!:) 代码(面积为200) 输出 广场的面积将是200.000000 这是另外三个数字。第一个数字是{0:d},第二个数字是{1:d}, 第三个数字是9 线程“Main

我只是在学习python并尝试一个非常简单的字符串格式行,但它不能正常工作。从下面的输出可以看出,它将数字插入3的最后一个,但前2个只是显示代码而不是数字。我确信解决方案很简单,但我试着看一下我的代码和学习材料中的代码,我看不出有什么区别。在Visual Studio 2015中使用Python 3.4

提前感谢您提供的任何帮助!:)

代码(面积为200)

输出

广场的面积将是200.000000

这是另外三个数字。第一个数字是{0:d},第二个数字是{1:d}, 第三个数字是9

线程“MainThread”(0xc10)已退出,代码为0(0x0)


程序“[4968]python.exe”已退出,代码为-1073741510(0xc000013a)。

您的字符串被分成两部分(实际上是三部分),但第一个字符串并不相关,因此我们将其忽略。但是,格式仅应用于最后一个字符串,在本例中,
“第三个数字是{2:d}”
,因此字符串
“第一个数字是{0:d},第二个数字是{1:d}”中的格式字符串将被忽略

对我有效的是以下代码:

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))

你有优先权问题。实际上,您所做的是包含三个字符串-
“这里还有三个其他数字。”
“第一个数字是{0:d},第二个数字是{1:d},\n”
“第三个数字是{2:d}”。格式(7,8,9)
format
调用仅应用于第三个字符串,因此仅替换
{2:d}

解决此问题的一种方法是用括号(
()
)包围您想要的字符串concatation,因此首先对其求值:

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))
但是一种更为简洁的方法是完全放弃字符串concatation,只使用多行字符串(注意缺少
+
操作符):


这里的问题是,format方法只针对添加在一起的3个字符串中的最后一个字符串调用。您应该在连接字符串后应用格式操作,或者使用接受换行符的单个字符串格式(因此您不必首先连接字符串)

要在串接后应用,只需在字符串串接周围使用一组额外的括号,例如

 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))

其中,
\
允许在不会打印的代码中换行。

哇,感谢大家快速、易懂的回答。我原以为该格式将应用于同一个括号内的所有{}字段,但是,现在我重新看看我所写的内容,因为串联将括号内的字符串分隔开,我认为单个括号内的所有字符串都包含在一起。谢谢您的帮助。你的回答很清楚,也很容易理解。
 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))