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

标签 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"

或者

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

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

最佳答案

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

关于Python - 带有 .format 或 %s 的多行 raw_input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315261/

相关文章:

c# - 格式字符串包含 "{"时出现 String.Format 异常

c# - 字符串格式不起作用

python - 对数据帧执行按位运算

python - 获取符号矩阵微分的计算图/表达式

python : How to search a large array in effiecient way?

python - 循环没有正确执行

python - 在 python 中显示 Youtube 剪辑

python - 如何让用户对 raw_input( ) 的响应访问同名字符串?

python - Python 的 raw_input() 中的制表符补全

c# - 如何通过 String.Format 格式化字符串