0

Let's say, I need to build a series of strings based on this pattern:

pattern="{app: }"

with an ultimate goal of generating the below sequence:

"{app: MS Office }"

"{app: Notepad }" etc.

I'm trying to do that using the format method, like so

insert="MS Office"
result=pattern.format(insert)

However, all I get back is

KeyError: 'app'

It does look like the error is caused by Python misinterpreting the colon in the pattern, but what how do I get around it? I do need the colon.

Thanks.

.

vanhemt
  • 165
  • 10
  • Possible duplicate of [How can I print literal curly-brace characters in python string and also use .format on it?](https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo) – awesoon Oct 23 '18 at 17:21

2 Answers2

1

You need to escape braces:

In [1]: pattern = '{{app: {}}}'

In [2]: pattern.format('MS Office')
Out[2]: '{app: MS Office}'
awesoon
  • 32,469
  • 11
  • 74
  • 99
  • Sure, it works. Could you _explain_ the double curly braces on the outside, please? – vanhemt Oct 23 '18 at 16:28
  • You need to escape `{` and `}` if you want to keep them in resulting string. `format` interprets `{app}` as a place to insert value passed as `app='something'` to the function – awesoon Oct 23 '18 at 17:22
  • And I'm escaping them with another set of curly braces? – vanhemt Oct 23 '18 at 18:40
  • [Yes](https://docs.python.org/3.3/library/string.html#format-string-syntax) – awesoon Oct 23 '18 at 18:43
1

Use

pattern="{{app: {0} }}"

insert="MS Office"
result=pattern.format(insert)
print(result)

Output:

{app: MS Office }
Rakesh
  • 81,458
  • 17
  • 76
  • 113