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?

3
  • Your string contains "{_}", which the format method will try to replace. Not sure if there's a way to escape it. Commented Oct 24, 2013 at 4:31
  • 2
    possible duplicate of How can I print a literal "{}" characters in python string and also use .format on it? Commented Oct 24, 2013 at 4:32
  • @Tim The way to escape it is in the first Related question. Commented Oct 24, 2013 at 4:32

1 Answer 1

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: '_'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.