Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 625cbf2

Browse files
committed
Modified parsing of format strings, so that we always return
a tuple (literal, field_name, format_spec, conversion). literal will always be a string, but might be of zero length. field_name will be None if there is no markup text format_spec will be a (possibly zero length) string if field_name is non-None conversion will be a one character string, or None This makes the Formatter class, and especially it's parse() method, easier to understand. Suggestion was by Jim Jewett, inspired by the "tail" of an elementtree node. Also, fixed a reference leak in fieldnameiter_next.
1 parent 9600f93 commit 625cbf2

2 files changed

Lines changed: 170 additions & 159 deletions

File tree

Lib/string.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,13 @@ def vformat(self, format_string, args, kwargs):
212212
result = []
213213
for literal_text, field_name, format_spec, conversion in \
214214
self.parse(format_string):
215-
if literal_text is None:
215+
216+
# output the literal text
217+
if literal_text:
218+
result.append(literal_text)
219+
220+
# if there's a field, output it
221+
if field_name is not None:
216222
# this is some markup, find the object and do
217223
# the formatting
218224

@@ -224,9 +230,7 @@ def vformat(self, format_string, args, kwargs):
224230

225231
# format the object and append to the result
226232
result.append(self.format_field(obj, format_spec))
227-
else:
228-
# this is literal text, use it directly
229-
result.append(literal_text)
233+
230234
self.check_unused_args(used_args, args, kwargs)
231235
return ''.join(result)
232236

@@ -263,6 +267,11 @@ def convert_field(self, value, conversion):
263267

264268
# returns an iterable that contains tuples of the form:
265269
# (literal_text, field_name, format_spec, conversion)
270+
# literal_text can be zero length
271+
# field_name can be None, in which case there's no
272+
# object to format and output
273+
# if field_name is not None, it is looked up, formatted
274+
# with format_spec and conversion and then used
266275
def parse(self, format_string):
267276
return format_string._formatter_parser()
268277

0 commit comments

Comments
 (0)