python三引号返回缩进字符串

Python triple quote returning indented string

我有以下代码:

1
2
3
4
5
6
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?
   """
)

它返回以下内容:

1
2
3
4
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行的缩进吗?


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

1
2
3
4
5
6
7
8
9
10
11
12
13
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?

如果可以对其进行修改,则手动删除前导空格更容易:

1
2
3
4
5
6
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?
"""
)

或者使用隐式字符串文字串联:

1
2
3
4
5
6
7
8
9
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?
'
)

如果以换行符(
结束字符串,则此选项将产生预期的结果。


可以使用Dedent函数。以下解决方案有3个优点

  • 不必在每行末尾添加
    字符,可以直接从外部源复制文本,
  • 我们可以保持函数的缩进,
  • 文本前后不插入多余的行

函数如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()

结果是:

1
2
3
4
5
6
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


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

一般来说,您的选择之一是使用:

1
2
3
4
5
6
7
8
9
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?"
    )

这就是所谓的隐式连接。


在您的原始代码中,在第一行之后,有一个缩进——三重引号字符串中的缩进是空白。所以你需要把它们去掉。

以下工作:

1
2
3
4
5
6
7
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()