Search code examples
pythonraw-inputstring.format

Python - multi-line raw_input with .format or %s


I want to do something functionally equivalent to this:

my_dict = {'option1': 'VALUE1', 'option2': 'VALUE2'}
def my_func():
    menu_option = raw_input(
        "Which option would you like to configure [0]?\n"
        "[0] NO CHANGES\n"
        "[1] Option1: \t{0}\n".format(my_dict.get('option1'))
        "[2] Option2: \t{0}\n".format(my_dict.get('option2'))
    ) or "0"

OR

my_dict = {'option1': 'VALUE1', 'option2': 'VALUE2'}
def my_func():
    menu_option = raw_input(
        "Which option would you like to configure [0]?\n"
        "[0] NO CHANGES\n"
        "[1] Option1: \t %s \n" % my_dict.get('option1')
        "[2] Option2: \t %s \n" % my_dict.get('option2')
    ) or "0"

Where the result of running my_func() looks like this:

Which option would you like to configure [0]?
[0] NO CHANGES
[1] Option1:     VALUE1
[2] Option2:     VALUE2

I'm getting an invalid syntax error. Is there a way to do this?


Solution

  • You are using multiline string while combining it with format calls; use either a multiline string with single format

    menu_option = raw_input("""
        Which option would you like to configure [0]?
        [0] NO CHANGES
        [1] Option1: \t{0}
        [2] Option2: \t{1}
        """.format(my_dict.get('option1'), my_dict.get('option2'))
    ) or "0"
    

    or add concatenation operators

    menu_option = raw_input(
        "Which option would you like to configure [0]?\n" + \
        "[0] NO CHANGES\n" + \
        "[1] Option1: \t{0}\n".format(my_dict.get('option1') + \
        "[2] Option2: \t{0}\n".format(my_dict.get('option2')
    ) or "0"