0

I'm struggling with multiline variable replacement by using format with named placeholders

port = 2000
replicaset = 'test'

print('''
  mongo --port {port} --eval '
    rs.initiate(
       {
          _id: "{replicaset}",
          version: 1,
          members: [
             { _id: 0, host : "localhost:{port}", priority: 1, votes: 1 },
          ]
       }
    )
  '
  '''.format(replicaset=replicaset, port=port))

The error I'm getting is the following

21:55 user@machine [machine-tag] ~$ python mongodb-setup.py
Traceback (most recent call last):
  File "mongodb-setup.py", line 59, in <module>
    '''.format(replicaset=replicaset, port=port))
KeyError: '\n        _id'
Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • You have braces in your format string, so `format` is trying to interpret that `{\n . _id: "… \n}` as a format spec, for a format argument named `_id` (with a conversion specifier that would be an error if you ever got that far, but you don't). – abarnert Sep 10 '18 at 20:09
  • OOoooohhhhh, OK! Thanks! – Daniel F Sep 10 '18 at 20:10
  • 1
    If you want to use literal braces in a format string, you need to escape them by doubling them, like `{{`. (I'm sure this is a dup of an existing question that explains things in detail.) – abarnert Sep 10 '18 at 20:10
  • Is there a way to specify the character used for wrapping a variable? – Daniel F Sep 10 '18 at 20:12
  • No; `str.format` (and f-strings) can only use `{}` braces. However, there's an older, completely different kind of string formatting using C-printf-style `%`, which is sometimes still useful—and strings with lots of stray braces but no percents is sometimes one of those uses. – abarnert Sep 10 '18 at 20:13

0 Answers0