Skip to content

CLN: replace %s syntax with .format in io/formats #17387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions pandas/io/formats/css.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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)
18 changes: 11 additions & 7 deletions pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
31 changes: 16 additions & 15 deletions pandas/io/formats/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -123,35 +123,36 @@ 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):
"""
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)
else:
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,
Expand Down Expand Up @@ -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)

Expand Down
45 changes: 26 additions & 19 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 = {
Expand All @@ -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)})
Expand All @@ -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),
Expand All @@ -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]
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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'):
"""
Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion pandas/io/formats/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))