2

Using python 2.7.4 and 3.3.1:

from textwrap import dedent as dd


name='Maruja'

print(dd('''
         {0}:
           _.-.
         '( ^{_}    (
           `~\`-----'\\
              )_)---)_)
         '''.format(name)))

It´s a key error in both:

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

With the % operator it works though:

from textwrap import dedent as dd


name ='Maruja'

print(dd('''
         %s:
           _.-.
         '( ^{_}    (
           `~\`-----'\\
              )_)---)_)
         ''' % name))

No error but why?

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

I have not been able to figure out why this happens and I have tested in several environments, what's wrong with it?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
HarmonicaMuse
  • 7,633
  • 37
  • 52
  • Your string contains `"{_}"`, which the `format` method will try to replace. Not sure if there's a way to escape it. – Tim Oct 24 '13 at 04:31
  • 2
    possible duplicate of [How can I print a literal "{}" characters in python string and also use .format on it?](http://stackoverflow.com/questions/5466451/how-can-i-print-a-literal-characters-in-python-string-and-also-use-format) – Barmar Oct 24 '13 at 04:32
  • @Tim The way to escape it is in the first **Related** question. – Barmar Oct 24 '13 at 04:32

1 Answers1

5

format method considers {_} also as one of the named placeholders and it is expecting a key:value pair with the key _. As it fails to find a match, it fails with KeyError: '_'

thefourtheye
  • 233,700
  • 52
  • 457
  • 497