Search code examples
python-3.xformat-string

How to allow '{' or '}' characters in a formatted python string


I need to print out a string similar to: "Field1: {Bob} Field2: {value}" Where the 1st field is constant, but the second field is formatted from some variable. I tried using a line like this:

field_str = "Field1: {Bob} Field2: {}".format(val)

But I get the error:

KeyError: 'Bob'

I'm pretty sure this is because the '{' and '}' characters in the string are being interpreted as something that needs to be formatted even though I want the string to contain those values. This is part of a much larger string, so I would prefer to not manually concatenate the strings together, but I would be ok with somehow adding format characters or something to get it to ignore the values that are inside "{}" in the string.

Is there any way to indicate that a '{' or '}' character is not intended for formatting in a string?


Solution

  • Use the double {{}} with python string formating f"...".

    val = 2
    
    field_str = f"Field1: {{Bob}} Field2: {val}"
    print(field_str)
    

    Output:

    Field1: {Bob} Field2: 2
    

    You may also pre-format the Bob value. For example

    val = 2
    field1 = '{Bob}'
    
    field_str = f"Field1: {field1} Field2: {val}"