带有格式调用的Python字符串中的键错误

时间:2018-01-10 18:59:55

标签: python string python-3.x

以下代码给出错误:

filename='foo.txt'
sed_str = 'PROJECT_DIR=\$\{PROJECT_DIR:-{}\}'.format(filename)
print (sed_str) 

结果:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 <ipython-input-12-9ac4d7cde75e> in <module>()
      1 filename='foo.txt'
----> 2 sed_str = 'PROJECT_DIR=\$\{PROJECT_DIR:-{}\}'.format(filename)
      3 print (sed_str)

KeyError: 'PROJECT_DIR'

为什么我会看到KeyError?

2 个答案:

答案 0 :(得分:0)

正如您对问题的评论中所提到的,您需要摆脱那些不需要格式化的花括号。以下是您遇到的问题的示例解决方案:

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> sed_str = 's#PROJECT_DIR=\$\{PROJECT_DIR:-.*\}#PROJECT_DIR=\$\{PROJECT_DIR:-{0}\}#'
>>> print(sed_str)
s#PROJECT_DIR=\$\{PROJECT_DIR:-.*\}#PROJECT_DIR=\$\{PROJECT_DIR:-{0}\}#
>>> sed_str = 's#PROJECT_DIR=\$\{{PROJECT_DIR:-.*\}}#PROJECT_DIR=\$\{{PROJECT_DIR:-{0}\}}#'.format('filename')
>>> print(sed_str)
s#PROJECT_DIR=\$\{PROJECT_DIR:-.*\}#PROJECT_DIR=\$\{PROJECT_DIR:-filename\}#
>>> 

如果您使用的是最新版本的Python,则可能需要考虑使用f''字符串来创建sed_str变量:

>>> path = 'filename'
>>> sed_str = f's#PROJECT_DIR=\$\{{PROJECT_DIR:-.*\}}#PROJECT_DIR=\$\{{PROJECT_DIR:-{path}\}}#'
>>> print(sed_str)
s#PROJECT_DIR=\$\{PROJECT_DIR:-.*\}#PROJECT_DIR=\$\{PROJECT_DIR:-filename\}#
>>> 

答案 1 :(得分:0)

使用{{}}转义格式字符串中的花括号:

filename='foo.txt'
sed_str = 'PROJECT_DIR=\$\{{PROJECT_DIR:-{}\}}'.format(filename)
print (sed_str) 

给出:

PROJECT_DIR=\$\{PROJECT_DIR:-foo.txt\}