Python三重引号返回缩进字符串
我有以下代码:Python三重引号返回缩进字符串,python,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 hone
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行的缩进吗?在您的原始代码中,第一行之后是缩进-三引号字符串中的缩进是空白。所以你需要去掉这些 以下工作:
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?
如果可以修改前导空格,则手动删除前导空格会容易得多:
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?
""")
或使用隐式:
如果以换行符(
\n
)结束字符串,此选项将产生预期结果。请检查此答案:
其中一个选项是使用隐式连接:
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?"
)
你可以使用这个功能。以下解决方案有3个优点
- 不必在每行末尾添加
字符,文本可以直接从外部源复制\n
- 我们可以保留函数的缩进
- 文本前后不插入额外的行
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
我认为您希望缩进其他字符串,以便第一个
“
AlignThank Jordan..但是使用您的代码会返回一个长句子。我将\n添加到每一行的末尾,该行完成了此操作。谢谢你的帮助。啊,我的错。是,\n
应添加到每行末尾。我编辑了答案。是的,那也行!然而,为了保持代码整洁,我会坚持上面乔丹的答案。因为“print”下的所有代码都位于“bear_room”函数中。谢谢。当然,如果有帮助的话,你可以投票给多个答案。你可以使用dedunt(s[1:])[:-1]
而不是dedunt(s).strip()
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