Skip to content

Commit b98e688

Browse files
cbertinatojreback
authored andcommitted
CLN: replace %s syntax with .format in io/formats/css.py, excel.py, printing.py, style.py, and terminal.py (pandas-dev#17387)
Progress toward issue pandas-dev#16130. Converted old string formatting to new string formatting in io/formats/css.py, excel.py, printing.py, style.py, and terminal.py
1 parent 64c8a8d commit b98e688

File tree

5 files changed

+71
-57
lines changed

5 files changed

+71
-57
lines changed

pandas/io/formats/css.py

+17-15
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,13 @@ def __call__(self, declarations_str, inherited=None):
9494

9595
# 3. TODO: resolve other font-relative units
9696
for side in self.SIDES:
97-
prop = 'border-%s-width' % side
97+
prop = 'border-{side}-width'.format(side=side)
9898
if prop in props:
9999
props[prop] = self.size_to_pt(
100100
props[prop], em_pt=font_size,
101101
conversions=self.BORDER_WIDTH_RATIOS)
102-
for prop in ['margin-%s' % side, 'padding-%s' % side]:
102+
for prop in ['margin-{side}'.format(side=side),
103+
'padding-{side}'.format(side=side)]:
103104
if prop in props:
104105
# TODO: support %
105106
props[prop] = self.size_to_pt(
@@ -152,7 +153,8 @@ def __call__(self, declarations_str, inherited=None):
152153

153154
def size_to_pt(self, in_val, em_pt=None, conversions=UNIT_RATIOS):
154155
def _error():
155-
warnings.warn('Unhandled size: %r' % in_val, CSSWarning)
156+
warnings.warn('Unhandled size: {val!r}'.format(val=in_val),
157+
CSSWarning)
156158
return self.size_to_pt('1!!default', conversions=conversions)
157159

158160
try:
@@ -185,10 +187,10 @@ def _error():
185187

186188
val = round(val, 5)
187189
if int(val) == val:
188-
size_fmt = '%d'
190+
size_fmt = '{fmt:d}pt'.format(fmt=int(val))
189191
else:
190-
size_fmt = '%f'
191-
return (size_fmt + 'pt') % val
192+
size_fmt = '{fmt:f}pt'.format(fmt=val)
193+
return size_fmt
192194

193195
def atomize(self, declarations):
194196
for prop, value in declarations:
@@ -215,19 +217,19 @@ def expand(self, prop, value):
215217
try:
216218
mapping = self.SIDE_SHORTHANDS[len(tokens)]
217219
except KeyError:
218-
warnings.warn('Could not expand "%s: %s"' % (prop, value),
219-
CSSWarning)
220+
warnings.warn('Could not expand "{prop}: {val}"'
221+
.format(prop=prop, val=value), CSSWarning)
220222
return
221223
for key, idx in zip(self.SIDES, mapping):
222-
yield prop_fmt % key, tokens[idx]
224+
yield prop_fmt.format(key), tokens[idx]
223225

224226
return expand
225227

226-
expand_border_color = _side_expander('border-%s-color')
227-
expand_border_style = _side_expander('border-%s-style')
228-
expand_border_width = _side_expander('border-%s-width')
229-
expand_margin = _side_expander('margin-%s')
230-
expand_padding = _side_expander('padding-%s')
228+
expand_border_color = _side_expander('border-{:s}-color')
229+
expand_border_style = _side_expander('border-{:s}-style')
230+
expand_border_width = _side_expander('border-{:s}-width')
231+
expand_margin = _side_expander('margin-{:s}')
232+
expand_padding = _side_expander('padding-{:s}')
231233

232234
def parse(self, declarations_str):
233235
"""Generates (prop, value) pairs from declarations
@@ -245,4 +247,4 @@ def parse(self, declarations_str):
245247
yield prop, val
246248
else:
247249
warnings.warn('Ill-formatted attribute: expected a colon '
248-
'in %r' % decl, CSSWarning)
250+
'in {decl!r}'.format(decl=decl), CSSWarning)

pandas/io/formats/excel.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,12 @@ def build_alignment(self, props):
132132

133133
def build_border(self, props):
134134
return {side: {
135-
'style': self._border_style(props.get('border-%s-style' % side),
136-
props.get('border-%s-width' % side)),
135+
'style': self._border_style(props.get('border-{side}-style'
136+
.format(side=side)),
137+
props.get('border-{side}-width'
138+
.format(side=side))),
137139
'color': self.color_to_excel(
138-
props.get('border-%s-color' % side)),
140+
props.get('border-{side}-color'.format(side=side))),
139141
} for side in ['top', 'right', 'bottom', 'left']}
140142

141143
def _border_style(self, style, width):
@@ -302,7 +304,8 @@ def color_to_excel(self, val):
302304
try:
303305
return self.NAMED_COLORS[val]
304306
except KeyError:
305-
warnings.warn('Unhandled colour format: %r' % val, CSSWarning)
307+
warnings.warn('Unhandled colour format: {val!r}'.format(val=val),
308+
CSSWarning)
306309

307310

308311
class ExcelFormatter(object):
@@ -369,7 +372,7 @@ def _format_value(self, val):
369372
if lib.isposinf_scalar(val):
370373
val = self.inf_rep
371374
elif lib.isneginf_scalar(val):
372-
val = '-%s' % self.inf_rep
375+
val = '-{inf}'.format(inf=self.inf_rep)
373376
elif self.float_format is not None:
374377
val = float(self.float_format % val)
375378
return val
@@ -434,8 +437,9 @@ def _format_header_regular(self):
434437
colnames = self.columns
435438
if has_aliases:
436439
if len(self.header) != len(self.columns):
437-
raise ValueError('Writing %d cols but got %d aliases' %
438-
(len(self.columns), len(self.header)))
440+
raise ValueError('Writing {cols} cols but got {alias} '
441+
'aliases'.format(cols=len(self.columns),
442+
alias=len(self.header)))
439443
else:
440444
colnames = self.header
441445

pandas/io/formats/printing.py

+16-15
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,9 @@ def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds):
102102
bounds length of printed sequence, depending on options
103103
"""
104104
if isinstance(seq, set):
105-
fmt = u("{%s}")
105+
fmt = u("{{{body}}}")
106106
else:
107-
fmt = u("[%s]") if hasattr(seq, '__setitem__') else u("(%s)")
107+
fmt = u("[{body}]") if hasattr(seq, '__setitem__') else u("({body})")
108108

109109
if max_seq_items is False:
110110
nitems = len(seq)
@@ -123,35 +123,36 @@ def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds):
123123
elif isinstance(seq, tuple) and len(seq) == 1:
124124
body += ','
125125

126-
return fmt % body
126+
return fmt.format(body=body)
127127

128128

129129
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
130130
"""
131131
internal. pprinter for iterables. you should probably use pprint_thing()
132132
rather then calling this directly.
133133
"""
134-
fmt = u("{%s}")
134+
fmt = u("{{{things}}}")
135135
pairs = []
136136

137-
pfmt = u("%s: %s")
137+
pfmt = u("{key}: {val}")
138138

139139
if max_seq_items is False:
140140
nitems = len(seq)
141141
else:
142142
nitems = max_seq_items or get_option("max_seq_items") or len(seq)
143143

144144
for k, v in list(seq.items())[:nitems]:
145-
pairs.append(pfmt %
146-
(pprint_thing(k, _nest_lvl + 1,
147-
max_seq_items=max_seq_items, **kwds),
148-
pprint_thing(v, _nest_lvl + 1,
149-
max_seq_items=max_seq_items, **kwds)))
145+
pairs.append(
146+
pfmt.format(
147+
key=pprint_thing(k, _nest_lvl + 1,
148+
max_seq_items=max_seq_items, **kwds),
149+
val=pprint_thing(v, _nest_lvl + 1,
150+
max_seq_items=max_seq_items, **kwds)))
150151

151152
if nitems < len(seq):
152-
return fmt % (", ".join(pairs) + ", ...")
153+
return fmt.format(things=", ".join(pairs) + ", ...")
153154
else:
154-
return fmt % ", ".join(pairs)
155+
return fmt.format(things=", ".join(pairs))
155156

156157

157158
def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
@@ -221,10 +222,10 @@ def as_escaped_unicode(thing, escape_chars=escape_chars):
221222
max_seq_items=max_seq_items)
222223
elif isinstance(thing, compat.string_types) and quote_strings:
223224
if compat.PY3:
224-
fmt = "'%s'"
225+
fmt = u("'{thing}'")
225226
else:
226-
fmt = "u'%s'"
227-
result = fmt % as_escaped_unicode(thing)
227+
fmt = u("u'{thing}'")
228+
result = fmt.format(thing=as_escaped_unicode(thing))
228229
else:
229230
result = as_escaped_unicode(thing)
230231

pandas/io/formats/style.py

+26-19
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def format_attr(pair):
230230
# ... except maybe the last for columns.names
231231
name = self.data.columns.names[r]
232232
cs = [BLANK_CLASS if name is None else INDEX_NAME_CLASS,
233-
"level%s" % r]
233+
"level{lvl}".format(lvl=r)]
234234
name = BLANK_VALUE if name is None else name
235235
row_es.append({"type": "th",
236236
"value": name,
@@ -240,7 +240,8 @@ def format_attr(pair):
240240

241241
if clabels:
242242
for c, value in enumerate(clabels[r]):
243-
cs = [COL_HEADING_CLASS, "level%s" % r, "col%s" % c]
243+
cs = [COL_HEADING_CLASS, "level{lvl}".format(lvl=r),
244+
"col{col}".format(col=c)]
244245
cs.extend(cell_context.get(
245246
"col_headings", {}).get(r, {}).get(c, []))
246247
es = {
@@ -264,7 +265,7 @@ def format_attr(pair):
264265

265266
for c, name in enumerate(self.data.index.names):
266267
cs = [INDEX_NAME_CLASS,
267-
"level%s" % c]
268+
"level{lvl}".format(lvl=c)]
268269
name = '' if name is None else name
269270
index_header_row.append({"type": "th", "value": name,
270271
"class": " ".join(cs)})
@@ -281,7 +282,8 @@ def format_attr(pair):
281282
for r, idx in enumerate(self.data.index):
282283
row_es = []
283284
for c, value in enumerate(rlabels[r]):
284-
rid = [ROW_HEADING_CLASS, "level%s" % c, "row%s" % r]
285+
rid = [ROW_HEADING_CLASS, "level{lvl}".format(lvl=c),
286+
"row{row}".format(row=r)]
285287
es = {
286288
"type": "th",
287289
"is_visible": _is_visible(r, c, idx_lengths),
@@ -298,7 +300,8 @@ def format_attr(pair):
298300
row_es.append(es)
299301

300302
for c, col in enumerate(self.data.columns):
301-
cs = [DATA_CLASS, "row%s" % r, "col%s" % c]
303+
cs = [DATA_CLASS, "row{row}".format(row=r),
304+
"col{col}".format(col=c)]
302305
cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
303306
formatter = self._display_funcs[(r, c)]
304307
value = self.data.iloc[r, c]
@@ -317,7 +320,8 @@ def format_attr(pair):
317320
else:
318321
props.append(['', ''])
319322
cellstyle.append({'props': props,
320-
'selector': "row%s_col%s" % (r, c)})
323+
'selector': "row{row}_col{col}"
324+
.format(row=r, col=c)})
321325
body.append(row_es)
322326

323327
return dict(head=head, cellstyle=cellstyle, body=body, uuid=uuid,
@@ -512,22 +516,23 @@ def _apply(self, func, axis=0, subset=None, **kwargs):
512516
result = func(data, **kwargs)
513517
if not isinstance(result, pd.DataFrame):
514518
raise TypeError(
515-
"Function {!r} must return a DataFrame when "
516-
"passed to `Styler.apply` with axis=None".format(func))
519+
"Function {func!r} must return a DataFrame when "
520+
"passed to `Styler.apply` with axis=None"
521+
.format(func=func))
517522
if not (result.index.equals(data.index) and
518523
result.columns.equals(data.columns)):
519-
msg = ('Result of {!r} must have identical index and columns '
520-
'as the input'.format(func))
524+
msg = ('Result of {func!r} must have identical index and '
525+
'columns as the input'.format(func=func))
521526
raise ValueError(msg)
522527

523528
result_shape = result.shape
524529
expected_shape = self.data.loc[subset].shape
525530
if result_shape != expected_shape:
526-
msg = ("Function {!r} returned the wrong shape.\n"
527-
"Result has shape: {}\n"
528-
"Expected shape: {}".format(func,
529-
result.shape,
530-
expected_shape))
531+
msg = ("Function {func!r} returned the wrong shape.\n"
532+
"Result has shape: {res}\n"
533+
"Expected shape: {expect}".format(func=func,
534+
res=result.shape,
535+
expect=expected_shape))
531536
raise ValueError(msg)
532537
self._update_ctx(result)
533538
return self
@@ -771,7 +776,8 @@ def set_table_styles(self, table_styles):
771776

772777
@staticmethod
773778
def _highlight_null(v, null_color):
774-
return 'background-color: %s' % null_color if pd.isna(v) else ''
779+
return ('background-color: {color}'.format(color=null_color)
780+
if pd.isna(v) else '')
775781

776782
def highlight_null(self, null_color='red'):
777783
"""
@@ -839,7 +845,8 @@ def _background_gradient(s, cmap='PuBu', low=0, high=0):
839845
# https://github.com/matplotlib/matplotlib/issues/5427
840846
normed = norm(s.values)
841847
c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
842-
return ['background-color: %s' % color for color in c]
848+
return ['background-color: {color}'.format(color=color)
849+
for color in c]
843850

844851
def set_properties(self, subset=None, **kwargs):
845852
"""
@@ -1182,6 +1189,6 @@ def _maybe_wrap_formatter(formatter):
11821189
elif callable(formatter):
11831190
return formatter
11841191
else:
1185-
msg = "Expected a template string or callable, got {} instead".format(
1186-
formatter)
1192+
msg = ("Expected a template string or callable, got {formatter} "
1193+
"instead".format(formatter=formatter))
11871194
raise TypeError(msg)

pandas/io/formats/terminal.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,4 @@ def ioctl_GWINSZ(fd):
124124

125125
if __name__ == "__main__":
126126
sizex, sizey = get_terminal_size()
127-
print('width = %s height = %s' % (sizex, sizey))
127+
print('width = {w} height = {h}'.format(w=sizex, h=sizey))

0 commit comments

Comments
 (0)