【问题标题】:Very basic string formatting not working (Python)非常基本的字符串格式不起作用(Python)
【发布时间】:2015-09-03 13:01:44
【问题描述】:

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

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

代码(面积为 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)。

【问题讨论】:

    标签: python python-3.x string-formatting


    【解决方案1】:

    这里的问题是,格式方法只被调用用于将 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))
    

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

    【讨论】:

    • 感谢您的帮助。您的回答非常清晰易懂。
    【解决方案2】:

    你有一个优先级问题。您实际上在做的是连接三个字符串 - "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) 的结果。 format 调用仅适用于第三个字符串,因此仅替换 {2: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))
    

    但更简洁的方法是完全放弃字符串连接,只使用多行字符串(注意缺少+ 运算符):

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

    【讨论】:

    • 哇,感谢大家快速且易于理解的回复。我认为该格式将适用于同一括号内的所有 {} 字段,但是,现在我重新查看我所写的内容,因为连接已将括号内的字符串分隔开来,我认为所有字符串都在其中一个括号内的内容一起包含在内。
    【解决方案3】:

    您的字符串被分成两部分(实际上是三部分),但第一个字符串并不真正相关,因此我们将其省略。但是,格式仅适用于最后一个字符串,在本例中为 "third number is {2:d}",因此字符串 "First number is {0:d}, second number is {1:d}, \n" 中的格式字符串将被忽略。

    对我有用的是以下代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2016-09-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      相关资源
      最近更新 更多