Skip to content

CLN-29547 replace old string formatting #31878

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

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 4 additions & 4 deletions pandas/_libs/tslibs/c_timestamp.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ def integer_op_not_supported(obj):

# GH#30886 using an fstring raises SystemError
int_addsub_msg = (
"Addition/subtraction of integers and integer-arrays with {cls} is "
"no longer supported. Instead of adding/subtracting `n`, "
"use `n * obj.freq`"
).format(cls=cls)
f"Addition/subtraction of integers and integer-arrays with {cls} is "
f"no longer supported. Instead of adding/subtracting `n`, "
f"use `n * obj.freq`"
)
return TypeError(int_addsub_msg)


Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ cdef inline int64_t parse_iso_format_string(object ts) except? -1:
bint have_dot = 0, have_value = 0, neg = 0
list number = [], unit = []

err_msg = "Invalid ISO 8601 Duration format - {}".format(ts)
err_msg = f"Invalid ISO 8601 Duration format - {ts}"

for c in ts:
# number (ascii codes)
Expand Down
16 changes: 7 additions & 9 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1126,8 +1126,8 @@ def __arrow_array__(self, type=None):
subtype = pyarrow.from_numpy_dtype(self.dtype.subtype)
except TypeError:
raise TypeError(
"Conversion to arrow with subtype '{}' "
"is not supported".format(self.dtype.subtype)
f"Conversion to arrow with subtype '{self.dtype.subtype}' "
f"is not supported"
)
interval_type = ArrowIntervalType(subtype, self.closed)
storage_array = pyarrow.StructArray.from_arrays(
Expand Down Expand Up @@ -1155,15 +1155,13 @@ def __arrow_array__(self, type=None):
# ensure we have the same subtype and closed attributes
if not type.equals(interval_type):
raise TypeError(
"Not supported to convert IntervalArray to type with "
"different 'subtype' ({0} vs {1}) and 'closed' ({2} vs {3}) "
"attributes".format(
self.dtype.subtype, type.subtype, self.closed, type.closed
)
f"Not supported to convert IntervalArray to type with "
f"different 'subtype' ({self.dtype.subtype} vs {type.subtype}) "
f"and 'closed' ({self.closed} vs {type.closed}) attributes"
)
else:
raise TypeError(
"Not supported to convert IntervalArray to '{0}' type".format(type)
f"Not supported to convert IntervalArray to '{type}' type"
)

return pyarrow.ExtensionArray.from_storage(interval_type, storage_array)
Expand All @@ -1175,7 +1173,7 @@ def __arrow_array__(self, type=None):

Parameters
----------
na_tuple : boolean, default True
na_tuple : bool, default True
Returns NA as a tuple if True, ``(nan, nan)``, or just as the NA
value itself if False, ``nan``.

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/util/hashing.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def hash_array(
elif issubclass(dtype.type, (np.datetime64, np.timedelta64)):
vals = vals.view("i8").astype("u8", copy=False)
elif issubclass(dtype.type, np.number) and dtype.itemsize <= 8:
vals = vals.view("u{}".format(vals.dtype.itemsize)).astype("u8")
vals = vals.view(f"u{vals.dtype.itemsize}").astype("u8")
else:
# With repeated values, its MUCH faster to categorize object dtypes,
# then hash and rename categories. We allow skipping the categorization
Expand Down
66 changes: 27 additions & 39 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def _get_footer(self) -> str:
if self.length:
if footer:
footer += ", "
footer += "Length: {length}".format(length=len(self.categorical))
footer += f"Length: {len(self.categorical)}"

level_info = self.categorical._repr_categories_info()

Expand Down Expand Up @@ -217,7 +217,7 @@ def to_string(self) -> str:

fmt_values = self._get_formatted_values()

fmt_values = ["{i}".format(i=i) for i in fmt_values]
fmt_values = [f"{i}" for i in fmt_values]
fmt_values = [i.strip() for i in fmt_values]
values = ", ".join(fmt_values)
result = ["[" + values + "]"]
Expand Down Expand Up @@ -301,28 +301,26 @@ def _get_footer(self) -> str:
assert isinstance(
self.series.index, (ABCDatetimeIndex, ABCPeriodIndex, ABCTimedeltaIndex)
)
footer += "Freq: {freq}".format(freq=self.series.index.freqstr)
footer += f"Freq: {self.series.index.freqstr}"

if self.name is not False and name is not None:
if footer:
footer += ", "

series_name = pprint_thing(name, escape_chars=("\t", "\r", "\n"))
footer += (
("Name: {sname}".format(sname=series_name)) if name is not None else ""
)
footer += f"Name: {series_name}" if name is not None else ""

if self.length is True or (self.length == "truncate" and self.truncate_v):
if footer:
footer += ", "
footer += "Length: {length}".format(length=len(self.series))
footer += f"Length: {len(self.series)}"

if self.dtype is not False and self.dtype is not None:
name = getattr(self.tr_series.dtype, "name", None)
if name:
if footer:
footer += ", "
footer += "dtype: {typ}".format(typ=pprint_thing(name))
footer += f"dtype: {pprint_thing(name)}"

# level infos are added to the end and in a new line, like it is done
# for Categoricals
Expand Down Expand Up @@ -359,9 +357,7 @@ def to_string(self) -> str:
footer = self._get_footer()

if len(series) == 0:
return "{name}([], {footer})".format(
name=type(self.series).__name__, footer=footer
)
return f"{type(self.series).__name__}([], {footer})"

fmt_index, have_header = self._get_formatted_index()
fmt_values = self._get_formatted_values()
Expand Down Expand Up @@ -584,10 +580,8 @@ def __init__(
self.formatters = formatters
else:
raise ValueError(
(
"Formatters length({flen}) should match "
"DataFrame number of columns({dlen})"
).format(flen=len(formatters), dlen=len(frame.columns))
f"Formatters length({len(formatters)}) should match "
f"DataFrame number of columns({len(frame.columns)})"
)
self.na_rep = na_rep
self.decimal = decimal
Expand Down Expand Up @@ -816,10 +810,10 @@ def write_result(self, buf: IO[str]) -> None:
frame = self.frame

if len(frame.columns) == 0 or len(frame.index) == 0:
info_line = "Empty {name}\nColumns: {col}\nIndex: {idx}".format(
name=type(self.frame).__name__,
col=pprint_thing(frame.columns),
idx=pprint_thing(frame.index),
info_line = (
f"Empty {type(self.frame).__name__}\n"
f"Columns: {pprint_thing(frame.columns)}\n"
f"Index: {pprint_thing(frame.index)}"
)
text = info_line
else:
Expand Down Expand Up @@ -865,11 +859,7 @@ def write_result(self, buf: IO[str]) -> None:
buf.writelines(text)

if self.should_show_dimensions:
buf.write(
"\n\n[{nrows} rows x {ncols} columns]".format(
nrows=len(frame), ncols=len(frame.columns)
)
)
buf.write(f"\n\n[{len(frame)} rows x {len(frame.columns)} columns]")

def _join_multiline(self, *args) -> str:
lwidth = self.line_width
Expand Down Expand Up @@ -1075,7 +1065,7 @@ def _get_formatted_index(self, frame: "DataFrame") -> List[str]:

# empty space for columns
if self.show_col_idx_names:
col_header = ["{x}".format(x=x) for x in self._get_column_name_list()]
col_header = [f"{x}" for x in self._get_column_name_list()]
else:
col_header = [""] * columns.nlevels

Expand Down Expand Up @@ -1211,10 +1201,8 @@ def _format_strings(self) -> List[str]:
if self.float_format is None:
float_format = get_option("display.float_format")
if float_format is None:
fmt_str = "{{x: .{prec:d}g}}".format(
prec=get_option("display.precision")
)
float_format = lambda x: fmt_str.format(x=x)
precision = get_option("display.precision")
float_format = lambda x: f"{x: .{precision:d}g}"
else:
float_format = self.float_format

Expand All @@ -1240,10 +1228,10 @@ def _format(x):
pass
return self.na_rep
elif isinstance(x, PandasObject):
return "{x}".format(x=x)
return f"{x}"
else:
# object dtype
return "{x}".format(x=formatter(x))
return f"{formatter(x)}"

vals = self.values
if isinstance(vals, Index):
Expand All @@ -1259,7 +1247,7 @@ def _format(x):
fmt_values = []
for i, v in enumerate(vals):
if not is_float_type[i] and leading_space:
fmt_values.append(" {v}".format(v=_format(v)))
fmt_values.append(f" {_format(v)}")
elif is_float_type[i]:
fmt_values.append(float_format(v))
else:
Expand All @@ -1268,8 +1256,8 @@ def _format(x):
# to include a space if we get here.
tpl = "{v}"
else:
tpl = " {v}"
fmt_values.append(tpl.format(v=_format(v)))
tpl = f" {_format(v)}"
fmt_values.append(tpl)

return fmt_values

Expand Down Expand Up @@ -1442,7 +1430,7 @@ def _format_strings(self) -> List[str]:

class IntArrayFormatter(GenericArrayFormatter):
def _format_strings(self) -> List[str]:
formatter = self.formatter or (lambda x: "{x: d}".format(x=x))
formatter = self.formatter or (lambda x: f"{x: d}")
fmt_values = [formatter(x) for x in self.values]
return fmt_values

Expand Down Expand Up @@ -1726,7 +1714,7 @@ def _formatter(x):
x = Timedelta(x)
result = x._repr_base(format=format)
if box:
result = "'{res}'".format(res=result)
result = f"'{result}'"
return result

return _formatter
Expand Down Expand Up @@ -1889,16 +1877,16 @@ def __call__(self, num: Union[int, float]) -> str:
prefix = self.ENG_PREFIXES[int_pow10]
else:
if int_pow10 < 0:
prefix = "E-{pow10:02d}".format(pow10=-int_pow10)
prefix = f"E-{-int_pow10:02d}"
else:
prefix = "E+{pow10:02d}".format(pow10=int_pow10)
prefix = f"E+{int_pow10:02d}"

mant = sign * dnum / (10 ** pow10)

if self.accuracy is None: # pragma: no cover
format_str = "{mant: g}{prefix}"
else:
format_str = "{{mant: .{acc:d}f}}{{prefix}}".format(acc=self.accuracy)
format_str = f"{{mant: .{self.accuracy:d}f}}{{prefix}}"

formatted = format_str.format(mant=mant, prefix=prefix)

Expand Down
29 changes: 11 additions & 18 deletions pandas/io/formats/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def __init__(
self.table_id = self.fmt.table_id
self.render_links = self.fmt.render_links
if isinstance(self.fmt.col_space, int):
self.fmt.col_space = "{colspace}px".format(colspace=self.fmt.col_space)
self.fmt.col_space = f"{self.fmt.col_space}px"

@property
def show_row_idx_names(self) -> bool:
Expand Down Expand Up @@ -124,7 +124,7 @@ def write_th(
"""
if header and self.fmt.col_space is not None:
tags = tags or ""
tags += 'style="min-width: {colspace};"'.format(colspace=self.fmt.col_space)
tags += f'style="min-width: {self.fmt.col_space};"'

self._write_cell(s, kind="th", indent=indent, tags=tags)

Expand All @@ -135,9 +135,9 @@ def _write_cell(
self, s: Any, kind: str = "td", indent: int = 0, tags: Optional[str] = None
) -> None:
if tags is not None:
start_tag = "<{kind} {tags}>".format(kind=kind, tags=tags)
start_tag = f"<{kind} {tags}>"
else:
start_tag = "<{kind}>".format(kind=kind)
start_tag = f"<{kind}>"

if self.escape:
# escape & first to prevent double escaping of &
Expand All @@ -149,16 +149,13 @@ def _write_cell(

if self.render_links and is_url(rs):
rs_unescaped = pprint_thing(s, escape_chars={}).strip()
start_tag += '<a href="{url}" target="_blank">'.format(url=rs_unescaped)
start_tag += f'<a href="{rs_unescaped}" target="_blank">'
end_a = "</a>"
else:
end_a = ""

self.write(
"{start}{rs}{end_a}</{kind}>".format(
start=start_tag, rs=rs, end_a=end_a, kind=kind
),
indent,
f"{start_tag}{rs}{end_a}</{kind}>", indent,
)

def write_tr(
Expand All @@ -177,7 +174,7 @@ def write_tr(
if align is None:
self.write("<tr>", indent)
else:
self.write('<tr style="text-align: {align};">'.format(align=align), indent)
self.write(f'<tr style="text-align: {align};">', indent)
indent += indent_delta

for i, s in enumerate(line):
Expand All @@ -196,9 +193,7 @@ def render(self) -> List[str]:
if self.should_show_dimensions:
by = chr(215) # ×
self.write(
"<p>{rows} rows {by} {cols} columns</p>".format(
rows=len(self.frame), by=by, cols=len(self.frame.columns)
)
f"<p>{len(self.frame)} rows {by} {len(self.frame.columns)} columns</p>"
)

return self.elements
Expand All @@ -216,20 +211,18 @@ def _write_table(self, indent: int = 0) -> None:
self.classes = self.classes.split()
if not isinstance(self.classes, (list, tuple)):
raise TypeError(
"classes must be a string, list, "
f"classes must be a string, list, "
f"or tuple, not {type(self.classes)}"
)
_classes.extend(self.classes)

if self.table_id is None:
id_section = ""
else:
id_section = ' id="{table_id}"'.format(table_id=self.table_id)
id_section = f' id="{self.table_id}"'

self.write(
'<table border="{border}" class="{cls}"{id_section}>'.format(
border=self.border, cls=" ".join(_classes), id_section=id_section
),
f'<table border="{self.border}" class="{" ".join(_classes)}"{id_section}>',
indent,
)

Expand Down
Loading