Python Format Throws Keyerror

Python format throws KeyError

You have a number of unescaped braces in that code. Python considers all braces to be placeholders and is trying to substitute them all. However, you have only supplied one value.

I expect that you don't want all your braces to be placeholders, so you should double the ones that you don't want substituted. Such as:

template = """                                                                  
function routes(app, model){{
app.get('/preNew{className}', function(req, res){{
res.render('{className}'.ejs, {{}});
}};
}});""".format(className=className)

I also took the liberty of using triple quotes for the string literal so you don't need the backslashes at the end of each line.

Format: KeyError when using curly brackets in strings

To insert a literal brace, double it up:

query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])

(This is documented here, but not highlighted particularly obviously).

str.format() raises KeyError

The problem is that those { and } characters you have there don't specify a key for formatting. You need to double them up, so change your code to:

addr_list_formatted.append("""
"{0}"
{{
"gamedir" "str"
"address" "{1}"
}}
""".format(addr_list_idx, addr))

Python String format with dynamic key throws KeyError

You can use positional placeholder {} instead of named ones.

So instead of:

x = "xdate({date1}, 'mm/dd/yyyy', {date2}, 'dd/mm/yyyy', {date3}, 'yyyy/mm/dd')"
yy = x.format(date1=v1, date2=v2, date3=v3)

do:

x = "xdate({}, 'mm/dd/yyyy', {}, 'dd/mm/yyyy', {}, 'yyyy/mm/dd')"
yy = x.format(v1, v2, v3)

Python format() Function KeyError

If you use a a named placeholder in the format string, you need to provide named arguments.

And you shouldn't have spaces around the name in the placeholder.

def hello( name="Sean", age=0 ):
return 'Hello, ' + name + " you are {age} years old".format(age=age)

Python string.format KeyError

you could do it line by line using a dictionary and passing the dict as keyword arguments using **

d=dict()
d['model']=model
d['content']=data
d['theaders']=theaders

html = html.format(**d)

string.Formatter throws KeyError ''

There are two somewhat related problems here, the simple answer to how to debug is: you can't, at least not with print statements, or anything itself using string formatting because that happens during another string format and destroys the state of the formatter.

That it throws an error is caused by the fact that string.Formatter() doesn't support empty fields, this was an addition to the formatting going from 2.6 to 3.1 (and 2.7), which is in the C code, but not reflected in the string module.

You can simulate the new behavior by subclassing the class MyFormatter:

from __future__ import print_function

from string import Formatter
import sys

w = 10
x = dict(a=1, ab=2, abc=3)

if sys.version_info < (3,):
int_type = (int, long)
else:
int_type = (int)

class MyFormatter(Formatter):

def vformat(self, *args):
self._automatic = None
return super(MyFormatter, self).vformat(*args)

def get_value(self, key, args, kwargs):
if key == '':
if self._automatic is None:
self._automatic = 0
elif self._automatic == -1:
raise ValueError("cannot switch from manual field specification "
"to automatic field numbering")
key = self._automatic
self._automatic += 1
elif isinstance(key, int_type):
if self._automatic is None:
self._automatic = -1
elif self._automatic != -1:
raise ValueError("cannot switch from automatic field numbering "
"to manual field specification")
return super(MyFormatter, self).get_value(key, args, kwargs)

that should get rid of the KeyError. After that you should override the method format_field instead of parse:

if sys.version_info < (3,):
string_type = basestring
else:
string_type = str

class TrailingFormatter(MyFormatter):
def format_field(self, value, spec):
if isinstance(value, string_type) and len(spec) > 1 and spec[0] == 't':
value += spec[1] # append the extra character
spec = spec[2:]
return super(TrailingFormatter, self).format_field(value, spec)

kf = TrailingFormatter()
w = 10

for k in sorted(x):
v = x[k]
print(kf.format('key {:t:<{}} {}', k, w, v))

and get:

key a:         1
key ab: 2
key abc: 3

Note the format specifier (t) that introduces the trailing character in the format string.

The Python formatting routines are actually smart enough to let you insert the trailing character in the string just like the width formatting:

    print(kf.format('key {:t{}<{}} {}', k, ':', w, v))

gives the same result and lets you dynamically change the ':'

You can also change format_field to be:

    def format_field(self, value, spec):
if len(spec) > 1 and spec[0] == 't':
value = str(value) + spec[1] # append the extra character
spec = spec[2:]
return super(TrailingFormatter, self).format_field(value, spec)

and hand in any type:

print(kf.format('key {:t{}<{}} {}', (1, 2), '@', 10, 3))

to get:

key (1, 2)@    3

but since you convert the value to a string before handing it to Formatter.formatfield() that might get you a different result if str(val) gets you a different value than using {0}.format(val) and/or with options after t: that only apply to non-string types (such as + and -)

str.format raises KeyError with dict as parameter

you have to pass the dictionary using named parameter packing or format reverts back to positional to display a string representation of your dictionary (would "work" if s = "{}" for instance, but not what you want).

s.format(**{"a": 1, "b": 2})

This is easier to comprehend when using a variable:

d = {"a": 1, "b": 2}
s.format(d) # tries to shove "d" into 3-param/named format: wrong
s.format(**d) # unpacks arguments. Works because keys are compatible with format string

Python .format() added to an url but throws a KeyError

You need to escape any braces that are not part of a replacement field.

url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&callback_params={{"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}}&action=changePage¶ms={{"page":{}}}'

https://docs.python.org/3/library/string.html#format-string-syntax



Related Topics



Leave a reply



Submit