首页 > 解决方案 > 如何在没有逗号的情况下将多个值添加到字典中的单个键中?

问题描述

在我不久前提出的一个问题中,我尝试使用 PyInquirer 一次编辑 .txt 文件的多行。当我发现问题时,我尝试摆弄它。

这是代码:


question = [
    {
        'type': 'input',
        'name': 'text_lines',
        'message': '',
        'default': ('This is a test line\n' 'This is another test line\n')
    }
]

answer = prompt(question)
print('The file says:\n {}'.format(answer['text_line']))

如您所见,键'default'使用括号,但字符串之间没有逗号。当我在它们之间放置逗号时,TypeError: not all arguments converted during string formatting就会发生错误。我怎样才能用相同的键放置两个字符串???这让我感到困惑,因为即使使用方括号和大括号也不起作用。

我只想重新创建'default'上面没有逗号的密钥

编辑:我没有意识到这只是串联。谢谢你的回答!!

标签: pythonpython-3.xdictionary

解决方案


因为没有逗号,所以它不是一个元组:它是一个表达式求值,表达式是两个字符串的连接。在交互模式下尝试:

>>> ('This is a test line\n' 'This is another test line\n')
'This is a test line\nThis is another test line\n'

推荐阅读