尝试在一行上打印多行字符串(字符串存储为变量)

时间:2018-07-03 20:17:21

标签: python string-formatting multiline

我正在研究MIT的计算和编程课程入门,并且试图将多行字符串存储在一个变量中,该变量可用于程序与用户进行交互。

我知道"""用于用回车符输入长行代码并插入换行符(我认为我的说法有些准确)。

我遇到的是存储的字符串在我的代码中看起来很糟糕,使用三重引号看起来更干净,但是我仍然希望将其打印在一行上。我正在尝试将其存储在这样的变量中:

inputRequest = """
Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate the guess is correct.
"""

,我试图像这样在控制台中调用该变量:

print(inputRequest, end=" ")

,但它仍在三行中打印出来。有没有一种有效的方法可以使我的代码看起来不会凌乱?将字符串存储在变量中似乎是减少我的输入的好方法,当我需要调用特定的输出以与用户进行交互时,但是我敢肯定,有更好的方法可以做到这一点。谢谢!

5 个答案:

答案 0 :(得分:4)

您可以在每行的末尾添加反斜杠,以防止在字符串中打印换行符。

inputRequest = """\
    Enter 'h' to indicate the guess is too high. \
    Enter 'l' to indicate the guess is too low. \
    Enter 'c' to indicate the guess is correct. \
    """

print(inputRequest)

如果需要,也可以出于相同目的使用单独的字符串。

inputRequest = \
    "Enter 'h' to indicate the guess is too high. " \
    "Enter 'l' to indicate the guess is too low. " \
    "Enter 'c' to indicate the guess is correct. " \

print(inputRequest)

答案 1 :(得分:2)

您的问题是字符串包含固有的EOL字符。 print语句不会添加任何换行符,但是它们已经嵌入到您要打印的行中。您需要替换它们,例如:

print(inputRequest.replace("\n", "  ")

结果:

Enter 'h' to indicate the guess is too high.  Enter 'l' to indicate the guess is too low.  Enter 'c' to indicate the guess is correct.

答案 2 :(得分:1)

答案在这里到处都是。这是一个对您有用的实验。在IDE中输入以下行:

text = "This is string1. This is string2. This is string3"

现在在每个标点符号后按Enter手动设置字符串格式,您将获得:

text = "This is string1." \
       "This is string2." \
       "This is string3."

上面是字符串连接,将以一种“干净”的方式提供您想要的内容。公认的答案并非像“干净的”那样完全正确,而是因为:“争论的语义” XD

答案 3 :(得分:0)

您可以在多行上创建单行字符串:

inputRequest = ("Enter 'h' to indicate the guess is too high. "
                "Enter 'l' to indicate the guess is too low. "
                "Enter 'c' to indicate the guess is correct.")

答案 4 :(得分:-1)

以下代码将帮助您实现您想要做的事情:

print("Enter 'h' to indicate the guess is too high.",
"Enter 'l' to indicate the guess is too low.",
"Enter 'c' to indicate the guess is correct.")

或者您也可以替换引号。以下代码的第一行说明了这一点:

print('Enter "h" to indicate the guess is too high.',
  "Enter 'l' to indicate the guess is too low.",
  "Enter 'c' to indicate the guess is correct.")

希望这是您想要实现的目标,并且对您有所帮助;) 干杯!