Skip to content

Commit 32055fa

Browse files
3vtsroberthdevries
authored andcommitted
CLN: 29547 replace old string formatting 4 (pandas-dev#31963)
1 parent b4fa62a commit 32055fa

9 files changed

+29
-35
lines changed

pandas/tests/internals/test_internals.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -91,17 +91,15 @@ def create_block(typestr, placement, item_shape=None, num_offset=0):
9191
elif typestr in ("complex", "c16", "c8"):
9292
values = 1.0j * (mat.astype(typestr) + num_offset)
9393
elif typestr in ("object", "string", "O"):
94-
values = np.reshape(
95-
["A{i:d}".format(i=i) for i in mat.ravel() + num_offset], shape
96-
)
94+
values = np.reshape([f"A{i:d}" for i in mat.ravel() + num_offset], shape)
9795
elif typestr in ("b", "bool"):
9896
values = np.ones(shape, dtype=np.bool_)
9997
elif typestr in ("datetime", "dt", "M8[ns]"):
10098
values = (mat * 1e9).astype("M8[ns]")
10199
elif typestr.startswith("M8[ns"):
102100
# datetime with tz
103101
m = re.search(r"M8\[ns,\s*(\w+\/?\w*)\]", typestr)
104-
assert m is not None, "incompatible typestr -> {0}".format(typestr)
102+
assert m is not None, f"incompatible typestr -> {typestr}"
105103
tz = m.groups()[0]
106104
assert num_items == 1, "must have only 1 num items for a tz-aware"
107105
values = DatetimeIndex(np.arange(N) * 1e9, tz=tz)
@@ -607,9 +605,9 @@ def test_interleave(self):
607605

608606
# self
609607
for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]:
610-
mgr = create_mgr("a: {0}".format(dtype))
608+
mgr = create_mgr(f"a: {dtype}")
611609
assert mgr.as_array().dtype == dtype
612-
mgr = create_mgr("a: {0}; b: {0}".format(dtype))
610+
mgr = create_mgr(f"a: {dtype}; b: {dtype}")
613611
assert mgr.as_array().dtype == dtype
614612

615613
# will be converted according the actual dtype of the underlying
@@ -1136,7 +1134,7 @@ def __array__(self):
11361134
return np.array(self.value, dtype=self.dtype)
11371135

11381136
def __str__(self) -> str:
1139-
return "DummyElement({}, {})".format(self.value, self.dtype)
1137+
return f"DummyElement({self.value}, {self.dtype})"
11401138

11411139
def __repr__(self) -> str:
11421140
return str(self)

pandas/tests/io/excel/test_readers.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -596,7 +596,8 @@ def test_read_from_file_url(self, read_ext, datapath):
596596
# fails on some systems
597597
import platform
598598

599-
pytest.skip("failing on {}".format(" ".join(platform.uname()).strip()))
599+
platform_info = " ".join(platform.uname()).strip()
600+
pytest.skip(f"failing on {platform_info}")
600601

601602
tm.assert_frame_equal(url_table, local_table)
602603

@@ -957,7 +958,7 @@ def test_excel_passes_na_filter(self, read_ext, na_filter):
957958
def test_unexpected_kwargs_raises(self, read_ext, arg):
958959
# gh-17964
959960
kwarg = {arg: "Sheet1"}
960-
msg = r"unexpected keyword argument `{}`".format(arg)
961+
msg = fr"unexpected keyword argument `{arg}`"
961962

962963
with pd.ExcelFile("test1" + read_ext) as excel:
963964
with pytest.raises(TypeError, match=msg):

pandas/tests/io/excel/test_style.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,7 @@ def style(df):
4545
def assert_equal_style(cell1, cell2, engine):
4646
if engine in ["xlsxwriter", "openpyxl"]:
4747
pytest.xfail(
48-
reason=(
49-
"GH25351: failing on some attribute "
50-
"comparisons in {}".format(engine)
51-
)
48+
reason=(f"GH25351: failing on some attribute comparisons in {engine}")
5249
)
5350
# XXX: should find a better way to check equality
5451
assert cell1.alignment.__dict__ == cell2.alignment.__dict__
@@ -108,7 +105,7 @@ def custom_converter(css):
108105
for col1, col2 in zip(wb["frame"].columns, wb["styled"].columns):
109106
assert len(col1) == len(col2)
110107
for cell1, cell2 in zip(col1, col2):
111-
ref = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
108+
ref = f"{cell2.column}{cell2.row:d}"
112109
# XXX: this isn't as strong a test as ideal; we should
113110
# confirm that differences are exclusive
114111
if ref == "B2":
@@ -156,7 +153,7 @@ def custom_converter(css):
156153
for col1, col2 in zip(wb["frame"].columns, wb["custom"].columns):
157154
assert len(col1) == len(col2)
158155
for cell1, cell2 in zip(col1, col2):
159-
ref = "{cell2.column}{cell2.row:d}".format(cell2=cell2)
156+
ref = f"{cell2.column}{cell2.row:d}"
160157
if ref in ("B2", "C3", "D4", "B5", "C6", "D7", "B8", "B9"):
161158
assert not cell1.font.bold
162159
assert cell2.font.bold

pandas/tests/io/excel/test_writers.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def set_engine(engine, ext):
4141
which engine should be used to write Excel files. After executing
4242
the test it rolls back said change to the global option.
4343
"""
44-
option_name = "io.excel.{ext}.writer".format(ext=ext.strip("."))
44+
option_name = f"io.excel.{ext.strip('.')}.writer"
4545
prev_engine = get_option(option_name)
4646
set_option(option_name, engine)
4747
yield
@@ -1206,15 +1206,15 @@ def test_path_path_lib(self, engine, ext):
12061206
writer = partial(df.to_excel, engine=engine)
12071207

12081208
reader = partial(pd.read_excel, index_col=0)
1209-
result = tm.round_trip_pathlib(writer, reader, path="foo.{ext}".format(ext=ext))
1209+
result = tm.round_trip_pathlib(writer, reader, path=f"foo.{ext}")
12101210
tm.assert_frame_equal(result, df)
12111211

12121212
def test_path_local_path(self, engine, ext):
12131213
df = tm.makeDataFrame()
12141214
writer = partial(df.to_excel, engine=engine)
12151215

12161216
reader = partial(pd.read_excel, index_col=0)
1217-
result = tm.round_trip_pathlib(writer, reader, path="foo.{ext}".format(ext=ext))
1217+
result = tm.round_trip_pathlib(writer, reader, path=f"foo.{ext}")
12181218
tm.assert_frame_equal(result, df)
12191219

12201220
def test_merged_cell_custom_objects(self, merge_cells, path):

pandas/tests/io/excel/test_xlrd.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def test_read_xlrd_book(read_ext, frame):
3737

3838
# TODO: test for openpyxl as well
3939
def test_excel_table_sheet_by_index(datapath, read_ext):
40-
path = datapath("io", "data", "excel", "test1{}".format(read_ext))
40+
path = datapath("io", "data", "excel", f"test1{read_ext}")
4141
with pd.ExcelFile(path) as excel:
4242
with pytest.raises(xlrd.XLRDError):
4343
pd.read_excel(excel, "asdf")

pandas/tests/io/formats/test_console.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def test_detect_console_encoding_from_stdout_stdin(monkeypatch, empty, filled):
3434
# they have values filled.
3535
# GH 21552
3636
with monkeypatch.context() as context:
37-
context.setattr("sys.{}".format(empty), MockEncoding(""))
38-
context.setattr("sys.{}".format(filled), MockEncoding(filled))
37+
context.setattr(f"sys.{empty}", MockEncoding(""))
38+
context.setattr(f"sys.{filled}", MockEncoding(filled))
3939
assert detect_console_encoding() == filled
4040

4141

pandas/tests/io/formats/test_to_html.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ def test_to_html_border(option, result, expected):
300300
else:
301301
with option_context("display.html.border", option):
302302
result = result(df)
303-
expected = 'border="{}"'.format(expected)
303+
expected = f'border="{expected}"'
304304
assert expected in result
305305

306306

@@ -318,7 +318,7 @@ def test_to_html(biggie_df_fixture):
318318
assert isinstance(s, str)
319319

320320
df.to_html(columns=["B", "A"], col_space=17)
321-
df.to_html(columns=["B", "A"], formatters={"A": lambda x: "{x:.1f}".format(x=x)})
321+
df.to_html(columns=["B", "A"], formatters={"A": lambda x: f"{x:.1f}"})
322322

323323
df.to_html(columns=["B", "A"], float_format=str)
324324
df.to_html(columns=["B", "A"], col_space=12, float_format=str)
@@ -745,7 +745,7 @@ def test_to_html_with_col_space_units(unit):
745745
if isinstance(unit, int):
746746
unit = str(unit) + "px"
747747
for h in hdrs:
748-
expected = '<th style="min-width: {unit};">'.format(unit=unit)
748+
expected = f'<th style="min-width: {unit};">'
749749
assert expected in h
750750

751751

pandas/tests/io/formats/test_to_latex.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,10 @@ def test_to_latex_with_formatters(self):
117117

118118
formatters = {
119119
"datetime64": lambda x: x.strftime("%Y-%m"),
120-
"float": lambda x: "[{x: 4.1f}]".format(x=x),
121-
"int": lambda x: "0x{x:x}".format(x=x),
122-
"object": lambda x: "-{x!s}-".format(x=x),
123-
"__index__": lambda x: "index: {x}".format(x=x),
120+
"float": lambda x: f"[{x: 4.1f}]",
121+
"int": lambda x: f"0x{x:x}",
122+
"object": lambda x: f"-{x!s}-",
123+
"__index__": lambda x: f"index: {x}",
124124
}
125125
result = df.to_latex(formatters=dict(formatters))
126126

@@ -744,9 +744,7 @@ def test_to_latex_multiindex_names(self, name0, name1, axes):
744744

745745
idx_names = tuple(n or "{}" for n in names)
746746
idx_names_row = (
747-
"{idx_names[0]} & {idx_names[1]} & & & & \\\\\n".format(
748-
idx_names=idx_names
749-
)
747+
f"{idx_names[0]} & {idx_names[1]} & & & & \\\\\n"
750748
if (0 in axes and any(names))
751749
else ""
752750
)

pandas/tests/io/generate_legacy_storage_files.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -323,17 +323,17 @@ def write_legacy_pickles(output_dir):
323323
"This script generates a storage file for the current arch, system, "
324324
"and python version"
325325
)
326-
print(" pandas version: {0}".format(version))
327-
print(" output dir : {0}".format(output_dir))
326+
print(f" pandas version: {version}")
327+
print(f" output dir : {output_dir}")
328328
print(" storage format: pickle")
329329

330-
pth = "{0}.pickle".format(platform_name())
330+
pth = f"{platform_name()}.pickle"
331331

332332
fh = open(os.path.join(output_dir, pth), "wb")
333333
pickle.dump(create_pickle_data(), fh, pickle.HIGHEST_PROTOCOL)
334334
fh.close()
335335

336-
print("created pickle file: {pth}".format(pth=pth))
336+
print(f"created pickle file: {pth}")
337337

338338

339339
def write_legacy_file():

0 commit comments

Comments
 (0)