Python三重引用返回缩进字符串

时间:2016-01-03 17:31:26

标签: python

我有以下代码:

def bear_room():
    print("""There is a bear here
    The bear has a bunch of honey
    The fat bear is in front of another door
    How are you going to move the bear?
    """)

它返回以下内容:

There is a bear here
    The bear has a bunch of honey
    The fat bear is in front of another door
    How are you going to move the bear?

有人可以建议我如何摆脱第2,3和4行的缩进吗?

4 个答案:

答案 0 :(得分:2)

如果您无法修改该字符串文字(例如,它是在代码之外定义的),请使用inspect.cleandoc或等效字符:

def bear_room():
    print("""There is a bear here
The bear has a bunch of honey
The fat bear is in front of another door
How are you going to move the bear?""")

bear_room()

如果您可以修改它,则手动删除前导空格要容易得多:

In [2]: import inspect

In [3]: s = inspect.cleandoc("""There is a bear here
   ...:     The bear has a bunch of honey
   ...:     The fat bear is in front of another door
   ...:     How are you going to move the bear?
   ...: """)

In [4]: print(s)
There is a bear here
The bear has a bunch of honey
The fat bear is in front of another door
How are you going to move the bear?

或使用隐式string literal concatenation

def bear_room():
    print("""There is a bear here
The bear has a bunch of honey
The fat bear is in front of another door
How are you going to move the bear?
""")

如果您使用换行符(def bear_room(): print('There is a bear here\n' 'The bear has a bunch of honey\n' 'The fat bear is in front of another door\n' 'How are you going to move the bear?\n') )结束字符串,此选项将产生预期结果。

答案 1 :(得分:1)

请检查此答案:https://stackoverflow.com/a/2504457/1869597

一般来说,您可以选择使用:

def bear_room():
    print("There is a bear here\n"
          "The bear has a bunch of honey\n"
          "The fat bear is in front of another door\n"
          "How are you going to move the bear?"
    )

这称为隐式连接。

答案 2 :(得分:1)

可以使用dedent功能。以下解决方案具有3个优点

  • 一行不必在每行的末尾添加\n字符,文本可以直接从extern源复制,
  • 可以保留我们功能的缩进,
  • 在文字
  • 之前和之后没有插入额外的行

该功能如下所示:

from textwrap import dedent
dedentString = lambda s : dedent(s[1:])[:-1]

def bear_room():
    s="""
    There is a bear here
    The bear has a bunch of honey
    The fat bear is in front of another door
    How are you going to move the bear?
    """
    print("Start of string : ")
    print(dedentString(s))
    print("End of string")

bear_room()

结果是:

Start of string :
There is a bear here
The bear has a bunch of honey
The fat bear is in front of another door
How are you going to move the bear?
End of string

答案 3 :(得分:0)

在原始代码中,在第一行之后有缩进 - 三重引用字符串中的缩进是空格。所以你需要删除它们。

以下作品:

some_behaviour