Search code examples
python-3.xinputindentationmultiline

Multiline input prompt indentation interfering with output indentation


I have a function that prints the number of pixels found in an image and then asks the user how they would like to proceed. As long as the interpreter hasn't moved on from the function I want all the output to be indented accordingly.

One such 'sub output' (the input prompt) needs to be multiple lines. So I kick off with the 3*quote (''') followed by two spaces to create the indentation. At the end of the question 'how would you like to proceed?' I use a hard return. An extra indentation is assumed by the text editor so I remove it causing the following list of suggestions to line up flush with the input variable command. Here's how it looks:

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 problem with this is that the interpreter is acknowledging the indentation that separates the function body from the function statement as actual string contents, causing the output to look like this:

The source image contains 512 px.

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

    get all
    get unique

    |

The only way to avoid this is by breaking indentation in the interpreter. Although I know it works, it doesn't look very good. So what options do I have?

EDIT: Just because I have the screenshot_

enter image description here


Solution

  • One thing that you should keep in mind is that once you have start a multiline string declaration, all the text until it is closed is taken as is and syntax (ie, indentation) is no longer considered.

    You can start your multiline with an explicit new line so that everything in the multiline string can be indented together in code.

    IE.

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

    would print out the prompt with a new line on top, but the formatting of the text is more explicitly shown and should appear as seen.