多行输入提示缩进干扰输出缩进

Multiline input prompt indentation interfering with output indentation

我有一个函数可以打印在图像中找到的像素数,然后询问用户他们希望如何继续。只要解释器​​没有从函数中移出,我希望所有输出都相应地缩进。

一个这样的'sub output'(输入提示)需要多行。所以我从 3*quote (''') 开始,后跟两个空格来创建缩进。题的最后'how would you like to proceed?'我用的是hardreturn。文本编辑器采用额外的缩进,因此我将其删除,导致以下建议列表与输入变量 command 齐平。外观如下:

def returnColors():

  #
  # lots of code that does stuff...
  #

  print("The source image contains", lSize, "px.")       
  print("")                                                 
  command=input('''  What would you like to do? You can say:

  get all                                                   
  get unique                                                

  ''')                                                      

这个问题是解释器承认将函数体与函数语句分开的缩进作为实际字符串内容,导致输出如下所示:

The source image contains 512 px.

  What would you like to do? You can say...

    get all
    get unique

    |

避免这种情况的唯一方法是打破解释器中的缩进。虽然我知道它有效,但它看起来不太好。那么我有什么选择呢?

编辑: 只是因为我有截图_

你应该记住的一件事是,一旦你开始了多行字符串声明,所有文本直到它被关闭都被视为原样并且不再考虑语法(即缩进)。

您可以使用明确的新行开始多行,这样多行字符串中的所有内容都可以在代码中一起缩进。

IE.

command=input('''
  What would you like to do? You can say:

  get all                                                   
  get unique

  ''')    

会打印出顶部有新行的提示,但文本的格式显示得更明确,应该如所见。