Python - 带有.format或%s的多行raw_input

时间:2017-06-01 19:05:36

标签: python raw-input string.format

我想做一些与此功能相同的事情:

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"

运行my_func()的结果如下所示:

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

我收到了无效的语法错误。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

您正在使用多行字符串,同时将其与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"

或添加连接运算符

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"

答案 1 :(得分:0)

多行注释使用"""编写:

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