使用`str.format`函数但不使用%s语法时的键错误

Sal*_*apa 2 python string format string-formatting

使用python 2.7.4和3.3.1:

from textwrap import dedent as dd


name='Maruja'

print(dd('''
         {0}:
           _.-.
         '( ^{_}    (
           `~\`-----'\\
              )_)---)_)
         '''.format(name)))
Run Code Online (Sandbox Code Playgroud)

这是两个方面的关键错误:

$ python3 test.py    # or python2 test.py
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    '''.format(name)))
KeyError: '_'
Run Code Online (Sandbox Code Playgroud)

使用%运算符它可以工作:

from textwrap import dedent as dd


name ='Maruja'

print(dd('''
         %s:
           _.-.
         '( ^{_}    (
           `~\`-----'\\
              )_)---)_)
         ''' % name))
Run Code Online (Sandbox Code Playgroud)

没错,但为什么?

$ python3 test2.py    # or python2 test2.py
Maruja:
  _.-.
'( ^{_}    (
  `~\`-----'\
     )_)---)_)
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么会发生这种情况而且我已经在几个环境中进行了测试,它有什么问题?

the*_*eye 5

format方法{_}也考虑作为命名占位符之一,它期望键与键值对_.由于找不到匹配,它失败了KeyError: '_'