From 705cec892adf3ce1b91fde2ec4a3ebb930e46418 Mon Sep 17 00:00:00 2001 From: chris Date: Wed, 30 Aug 2017 20:21:07 -0400 Subject: [PATCH] CLN: replace %s syntax with .format in io/formats/css.py, excel.py, printing.py, style.py, and terminal.py Progress toward issue #16130. Converted old string formatting to new string formatting in io/formats/css.py, excel.py, printing.py, style.py, and terminal.py --- pandas/io/formats/css.py | 32 +++++++++++++------------ pandas/io/formats/excel.py | 18 ++++++++------ pandas/io/formats/printing.py | 31 ++++++++++++------------ pandas/io/formats/style.py | 45 ++++++++++++++++++++--------------- pandas/io/formats/terminal.py | 2 +- 5 files changed, 71 insertions(+), 57 deletions(-) diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py index d12d2373e1190..429c98b579ca0 100644 --- a/pandas/io/formats/css.py +++ b/pandas/io/formats/css.py @@ -94,12 +94,13 @@ def __call__(self, declarations_str, inherited=None): # 3. TODO: resolve other font-relative units for side in self.SIDES: - prop = 'border-%s-width' % side + prop = 'border-{side}-width'.format(side=side) if prop in props: props[prop] = self.size_to_pt( props[prop], em_pt=font_size, conversions=self.BORDER_WIDTH_RATIOS) - for prop in ['margin-%s' % side, 'padding-%s' % side]: + for prop in ['margin-{side}'.format(side=side), + 'padding-{side}'.format(side=side)]: if prop in props: # TODO: support % props[prop] = self.size_to_pt( @@ -152,7 +153,8 @@ def __call__(self, declarations_str, inherited=None): def size_to_pt(self, in_val, em_pt=None, conversions=UNIT_RATIOS): def _error(): - warnings.warn('Unhandled size: %r' % in_val, CSSWarning) + warnings.warn('Unhandled size: {val!r}'.format(val=in_val), + CSSWarning) return self.size_to_pt('1!!default', conversions=conversions) try: @@ -185,10 +187,10 @@ def _error(): val = round(val, 5) if int(val) == val: - size_fmt = '%d' + size_fmt = '{fmt:d}pt'.format(fmt=int(val)) else: - size_fmt = '%f' - return (size_fmt + 'pt') % val + size_fmt = '{fmt:f}pt'.format(fmt=val) + return size_fmt def atomize(self, declarations): for prop, value in declarations: @@ -215,19 +217,19 @@ def expand(self, prop, value): try: mapping = self.SIDE_SHORTHANDS[len(tokens)] except KeyError: - warnings.warn('Could not expand "%s: %s"' % (prop, value), - CSSWarning) + warnings.warn('Could not expand "{prop}: {val}"' + .format(prop=prop, val=value), CSSWarning) return for key, idx in zip(self.SIDES, mapping): - yield prop_fmt % key, tokens[idx] + yield prop_fmt.format(key), tokens[idx] return expand - expand_border_color = _side_expander('border-%s-color') - expand_border_style = _side_expander('border-%s-style') - expand_border_width = _side_expander('border-%s-width') - expand_margin = _side_expander('margin-%s') - expand_padding = _side_expander('padding-%s') + expand_border_color = _side_expander('border-{:s}-color') + expand_border_style = _side_expander('border-{:s}-style') + expand_border_width = _side_expander('border-{:s}-width') + expand_margin = _side_expander('margin-{:s}') + expand_padding = _side_expander('padding-{:s}') def parse(self, declarations_str): """Generates (prop, value) pairs from declarations @@ -245,4 +247,4 @@ def parse(self, declarations_str): yield prop, val else: warnings.warn('Ill-formatted attribute: expected a colon ' - 'in %r' % decl, CSSWarning) + 'in {decl!r}'.format(decl=decl), CSSWarning) diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 80c3880d39dfd..ab689d196f4b6 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -132,10 +132,12 @@ def build_alignment(self, props): def build_border(self, props): return {side: { - 'style': self._border_style(props.get('border-%s-style' % side), - props.get('border-%s-width' % side)), + 'style': self._border_style(props.get('border-{side}-style' + .format(side=side)), + props.get('border-{side}-width' + .format(side=side))), 'color': self.color_to_excel( - props.get('border-%s-color' % side)), + props.get('border-{side}-color'.format(side=side))), } for side in ['top', 'right', 'bottom', 'left']} def _border_style(self, style, width): @@ -302,7 +304,8 @@ def color_to_excel(self, val): try: return self.NAMED_COLORS[val] except KeyError: - warnings.warn('Unhandled colour format: %r' % val, CSSWarning) + warnings.warn('Unhandled colour format: {val!r}'.format(val=val), + CSSWarning) class ExcelFormatter(object): @@ -369,7 +372,7 @@ def _format_value(self, val): if lib.isposinf_scalar(val): val = self.inf_rep elif lib.isneginf_scalar(val): - val = '-%s' % self.inf_rep + val = '-{inf}'.format(inf=self.inf_rep) elif self.float_format is not None: val = float(self.float_format % val) return val @@ -434,8 +437,9 @@ def _format_header_regular(self): colnames = self.columns if has_aliases: if len(self.header) != len(self.columns): - raise ValueError('Writing %d cols but got %d aliases' % - (len(self.columns), len(self.header))) + raise ValueError('Writing {cols} cols but got {alias} ' + 'aliases'.format(cols=len(self.columns), + alias=len(self.header))) else: colnames = self.header diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index cbad603630bd3..e0f53f671017a 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -102,9 +102,9 @@ def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds): bounds length of printed sequence, depending on options """ if isinstance(seq, set): - fmt = u("{%s}") + fmt = u("{{{body}}}") else: - fmt = u("[%s]") if hasattr(seq, '__setitem__') else u("(%s)") + fmt = u("[{body}]") if hasattr(seq, '__setitem__') else u("({body})") if max_seq_items is False: nitems = len(seq) @@ -123,7 +123,7 @@ def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds): elif isinstance(seq, tuple) and len(seq) == 1: body += ',' - return fmt % body + return fmt.format(body=body) def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds): @@ -131,10 +131,10 @@ def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds): internal. pprinter for iterables. you should probably use pprint_thing() rather then calling this directly. """ - fmt = u("{%s}") + fmt = u("{{{things}}}") pairs = [] - pfmt = u("%s: %s") + pfmt = u("{key}: {val}") if max_seq_items is False: nitems = len(seq) @@ -142,16 +142,17 @@ def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds): nitems = max_seq_items or get_option("max_seq_items") or len(seq) for k, v in list(seq.items())[:nitems]: - pairs.append(pfmt % - (pprint_thing(k, _nest_lvl + 1, - max_seq_items=max_seq_items, **kwds), - pprint_thing(v, _nest_lvl + 1, - max_seq_items=max_seq_items, **kwds))) + pairs.append( + pfmt.format( + key=pprint_thing(k, _nest_lvl + 1, + max_seq_items=max_seq_items, **kwds), + val=pprint_thing(v, _nest_lvl + 1, + max_seq_items=max_seq_items, **kwds))) if nitems < len(seq): - return fmt % (", ".join(pairs) + ", ...") + return fmt.format(things=", ".join(pairs) + ", ...") else: - return fmt % ", ".join(pairs) + return fmt.format(things=", ".join(pairs)) 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): max_seq_items=max_seq_items) elif isinstance(thing, compat.string_types) and quote_strings: if compat.PY3: - fmt = "'%s'" + fmt = u("'{thing}'") else: - fmt = "u'%s'" - result = fmt % as_escaped_unicode(thing) + fmt = u("u'{thing}'") + result = fmt.format(thing=as_escaped_unicode(thing)) else: result = as_escaped_unicode(thing) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 445fceb4b8146..87d672197be30 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -230,7 +230,7 @@ def format_attr(pair): # ... except maybe the last for columns.names name = self.data.columns.names[r] cs = [BLANK_CLASS if name is None else INDEX_NAME_CLASS, - "level%s" % r] + "level{lvl}".format(lvl=r)] name = BLANK_VALUE if name is None else name row_es.append({"type": "th", "value": name, @@ -240,7 +240,8 @@ def format_attr(pair): if clabels: for c, value in enumerate(clabels[r]): - cs = [COL_HEADING_CLASS, "level%s" % r, "col%s" % c] + cs = [COL_HEADING_CLASS, "level{lvl}".format(lvl=r), + "col{col}".format(col=c)] cs.extend(cell_context.get( "col_headings", {}).get(r, {}).get(c, [])) es = { @@ -264,7 +265,7 @@ def format_attr(pair): for c, name in enumerate(self.data.index.names): cs = [INDEX_NAME_CLASS, - "level%s" % c] + "level{lvl}".format(lvl=c)] name = '' if name is None else name index_header_row.append({"type": "th", "value": name, "class": " ".join(cs)}) @@ -281,7 +282,8 @@ def format_attr(pair): for r, idx in enumerate(self.data.index): row_es = [] for c, value in enumerate(rlabels[r]): - rid = [ROW_HEADING_CLASS, "level%s" % c, "row%s" % r] + rid = [ROW_HEADING_CLASS, "level{lvl}".format(lvl=c), + "row{row}".format(row=r)] es = { "type": "th", "is_visible": _is_visible(r, c, idx_lengths), @@ -298,7 +300,8 @@ def format_attr(pair): row_es.append(es) for c, col in enumerate(self.data.columns): - cs = [DATA_CLASS, "row%s" % r, "col%s" % c] + cs = [DATA_CLASS, "row{row}".format(row=r), + "col{col}".format(col=c)] cs.extend(cell_context.get("data", {}).get(r, {}).get(c, [])) formatter = self._display_funcs[(r, c)] value = self.data.iloc[r, c] @@ -317,7 +320,8 @@ def format_attr(pair): else: props.append(['', '']) cellstyle.append({'props': props, - 'selector': "row%s_col%s" % (r, c)}) + 'selector': "row{row}_col{col}" + .format(row=r, col=c)}) body.append(row_es) return dict(head=head, cellstyle=cellstyle, body=body, uuid=uuid, @@ -512,22 +516,23 @@ def _apply(self, func, axis=0, subset=None, **kwargs): result = func(data, **kwargs) if not isinstance(result, pd.DataFrame): raise TypeError( - "Function {!r} must return a DataFrame when " - "passed to `Styler.apply` with axis=None".format(func)) + "Function {func!r} must return a DataFrame when " + "passed to `Styler.apply` with axis=None" + .format(func=func)) if not (result.index.equals(data.index) and result.columns.equals(data.columns)): - msg = ('Result of {!r} must have identical index and columns ' - 'as the input'.format(func)) + msg = ('Result of {func!r} must have identical index and ' + 'columns as the input'.format(func=func)) raise ValueError(msg) result_shape = result.shape expected_shape = self.data.loc[subset].shape if result_shape != expected_shape: - msg = ("Function {!r} returned the wrong shape.\n" - "Result has shape: {}\n" - "Expected shape: {}".format(func, - result.shape, - expected_shape)) + msg = ("Function {func!r} returned the wrong shape.\n" + "Result has shape: {res}\n" + "Expected shape: {expect}".format(func=func, + res=result.shape, + expect=expected_shape)) raise ValueError(msg) self._update_ctx(result) return self @@ -771,7 +776,8 @@ def set_table_styles(self, table_styles): @staticmethod def _highlight_null(v, null_color): - return 'background-color: %s' % null_color if pd.isna(v) else '' + return ('background-color: {color}'.format(color=null_color) + if pd.isna(v) else '') def highlight_null(self, null_color='red'): """ @@ -839,7 +845,8 @@ def _background_gradient(s, cmap='PuBu', low=0, high=0): # https://github.com/matplotlib/matplotlib/issues/5427 normed = norm(s.values) c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)] - return ['background-color: %s' % color for color in c] + return ['background-color: {color}'.format(color=color) + for color in c] def set_properties(self, subset=None, **kwargs): """ @@ -1182,6 +1189,6 @@ def _maybe_wrap_formatter(formatter): elif callable(formatter): return formatter else: - msg = "Expected a template string or callable, got {} instead".format( - formatter) + msg = ("Expected a template string or callable, got {formatter} " + "instead".format(formatter=formatter)) raise TypeError(msg) diff --git a/pandas/io/formats/terminal.py b/pandas/io/formats/terminal.py index 30bd1d16b538a..4bcb28fa59b86 100644 --- a/pandas/io/formats/terminal.py +++ b/pandas/io/formats/terminal.py @@ -124,4 +124,4 @@ def ioctl_GWINSZ(fd): if __name__ == "__main__": sizex, sizey = get_terminal_size() - print('width = %s height = %s' % (sizex, sizey)) + print('width = {w} height = {h}'.format(w=sizex, h=sizey))