6

The following code causes an Invalid Format Specifier when the string is converted to an f-string. I can't pinpoint what the problem is as my quotations look okay.

expected_document = f'{"name":"tenders","value":"chicken","key":"{key}"}'

causes:

>       expected_document = f'{"name":"tenders","value":"chicken","key":"{key}"}'
E       ValueError: Invalid format specifier

while removing the f:

expected_document = '{"name":"tenders","value":"chicken","key":"{key}"}'

works fine.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
tenders27
  • 61
  • 1
  • 2

3 Answers3

7

Why use f-string at all?

The following code works.

key = 'test'

expected_document = { "name": "tenders", "value": "chicken", "key": key }

print(expected_document)

Output:

{'name': 'tenders', 'value': 'chicken', 'key': 'test'}

Update #1: If you want it as a string and don't want to do type conversion, then...

key = 'test'

expected_document_1 = '{"name":"tenders","value":"chicken","key":"' + key + '"}'  # old fashioned way

print(expected_document_1)

expected_document_2 = f'{{"name":"tenders","value":"chicken","key":"{key}"}}'  # using f-string

print(expected_document_2)

Output:

{"name":"tenders","value":"chicken","key":"test"}
{"name":"tenders","value":"chicken","key":"test"}

Update #2: @Error - Syntactical Remorse had already suggested the second option of escaping the braces in one of the comments.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
  • Because I need expected_document to be a string, I'm asserting it equals another string where key could change. Maybe it's possible I could change types of that string to a dictionary or something? – tenders27 Aug 01 '19 at 17:52
0

I think you can just put the f inside the dict like this:

key = 'test'

expected_document = {"name":"tenders","value":"chicken","key":f"{key}"}
bbd108
  • 958
  • 2
  • 10
  • 26
0

You could compile the dictionary without using interpolation and then convert it to a string.

temporary_variable = {"name": "tenders", "value": "chicken", "key": key}
expected_document = str(temporary_variable)

Or you could even put this in one line.

expected_document = str({"name": "tenders", "value": "chicken", "key": key})

I am using Python 3.6.3 - I don't know how other versions would handle this. A potential drawback of this is that you shouldn't rely on dictionaries to maintain their order, which could cause this to break.

Jacinator
  • 1,413
  • 8
  • 11