Skip to content

Commit fe4c34b

Browse files
AaronCritchleyjreback
authored andcommitted
CLN: replace %s syntax with .format in tests.io.formats/json/sas (#18351)
1 parent cfad581 commit fe4c34b

File tree

9 files changed

+68
-56
lines changed

9 files changed

+68
-56
lines changed

pandas/tests/io/formats/test_css.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -69,25 +69,25 @@ def test_css_parse_invalid(invalid_css, remainder):
6969
def test_css_side_shorthands(shorthand, expansions):
7070
top, right, bottom, left = expansions
7171

72-
assert_resolves('%s: 1pt' % shorthand,
72+
assert_resolves('{shorthand}: 1pt'.format(shorthand=shorthand),
7373
{top: '1pt', right: '1pt',
7474
bottom: '1pt', left: '1pt'})
7575

76-
assert_resolves('%s: 1pt 4pt' % shorthand,
76+
assert_resolves('{shorthand}: 1pt 4pt'.format(shorthand=shorthand),
7777
{top: '1pt', right: '4pt',
7878
bottom: '1pt', left: '4pt'})
7979

80-
assert_resolves('%s: 1pt 4pt 2pt' % shorthand,
80+
assert_resolves('{shorthand}: 1pt 4pt 2pt'.format(shorthand=shorthand),
8181
{top: '1pt', right: '4pt',
8282
bottom: '2pt', left: '4pt'})
8383

84-
assert_resolves('%s: 1pt 4pt 2pt 0pt' % shorthand,
84+
assert_resolves('{shorthand}: 1pt 4pt 2pt 0pt'.format(shorthand=shorthand),
8585
{top: '1pt', right: '4pt',
8686
bottom: '2pt', left: '0pt'})
8787

8888
with tm.assert_produces_warning(CSSWarning):
89-
assert_resolves('%s: 1pt 1pt 1pt 1pt 1pt' % shorthand,
90-
{})
89+
assert_resolves(
90+
'{shorthand}: 1pt 1pt 1pt 1pt 1pt'.format(shorthand=shorthand), {})
9191

9292

9393
@pytest.mark.parametrize('style,inherited,equiv', [
@@ -127,10 +127,10 @@ def test_css_none_absent(style, equiv):
127127

128128
@pytest.mark.parametrize('size,resolved', [
129129
('xx-small', '6pt'),
130-
('x-small', '%fpt' % 7.5),
131-
('small', '%fpt' % 9.6),
130+
('x-small', '{pt:f}pt'.format(pt=7.5)),
131+
('small', '{pt:f}pt'.format(pt=9.6)),
132132
('medium', '12pt'),
133-
('large', '%fpt' % 13.5),
133+
('large', '{pt:f}pt'.format(pt=13.5)),
134134
('x-large', '18pt'),
135135
('xx-large', '24pt'),
136136
@@ -149,8 +149,8 @@ def test_css_absolute_font_size(size, relative_to, resolved):
149149
inherited = None
150150
else:
151151
inherited = {'font-size': relative_to}
152-
assert_resolves('font-size: %s' % size, {'font-size': resolved},
153-
inherited=inherited)
152+
assert_resolves('font-size: {size}'.format(size=size),
153+
{'font-size': resolved}, inherited=inherited)
154154

155155

156156
@pytest.mark.parametrize('size,relative_to,resolved', [
@@ -174,13 +174,13 @@ def test_css_absolute_font_size(size, relative_to, resolved):
174174
175175
('smaller', None, '10pt'),
176176
('smaller', '18pt', '15pt'),
177-
('larger', None, '%fpt' % 14.4),
177+
('larger', None, '{pt:f}pt'.format(pt=14.4)),
178178
('larger', '15pt', '18pt'),
179179
])
180180
def test_css_relative_font_size(size, relative_to, resolved):
181181
if relative_to is None:
182182
inherited = None
183183
else:
184184
inherited = {'font-size': relative_to}
185-
assert_resolves('font-size: %s' % size, {'font-size': resolved},
186-
inherited=inherited)
185+
assert_resolves('font-size: {size}'.format(size=size),
186+
{'font-size': resolved}, inherited=inherited)

pandas/tests/io/formats/test_format.py

+14-13
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ def test_repr_max_columns_max_rows(self):
313313
"{0} x {1}".format(term_width, term_height))
314314

315315
def mkframe(n):
316-
index = ['%05d' % i for i in range(n)]
316+
index = ['{i:05d}'.format(i=i) for i in range(n)]
317317
return DataFrame(0, index, index)
318318

319319
df6 = mkframe(6)
@@ -465,9 +465,9 @@ def test_to_string_with_formatters(self):
465465
'object': [(1, 2), True, False]},
466466
columns=['int', 'float', 'object'])
467467

468-
formatters = [('int', lambda x: '0x%x' % x),
469-
('float', lambda x: '[% 4.1f]' % x),
470-
('object', lambda x: '-%s-' % str(x))]
468+
formatters = [('int', lambda x: '0x{x:x}'.format(x=x)),
469+
('float', lambda x: '[{x: 4.1f}]'.format(x=x)),
470+
('object', lambda x: '-{x!s}-'.format(x=x))]
471471
result = df.to_string(formatters=dict(formatters))
472472
result2 = df.to_string(formatters=lzip(*formatters)[1])
473473
assert result == (' int float object\n'
@@ -500,7 +500,8 @@ def format_func(x):
500500

501501
def test_to_string_with_formatters_unicode(self):
502502
df = DataFrame({u('c/\u03c3'): [1, 2, 3]})
503-
result = df.to_string(formatters={u('c/\u03c3'): lambda x: '%s' % x})
503+
result = df.to_string(
504+
formatters={u('c/\u03c3'): lambda x: '{x}'.format(x=x)})
504505
assert result == u(' c/\u03c3\n') + '0 1\n1 2\n2 3'
505506

506507
def test_east_asian_unicode_frame(self):
@@ -944,7 +945,7 @@ def test_wide_repr(self):
944945
set_option('display.expand_frame_repr', False)
945946
rep_str = repr(df)
946947

947-
assert "10 rows x %d columns" % (max_cols - 1) in rep_str
948+
assert "10 rows x {c} columns".format(c=max_cols - 1) in rep_str
948949
set_option('display.expand_frame_repr', True)
949950
wide_repr = repr(df)
950951
assert rep_str != wide_repr
@@ -1056,7 +1057,7 @@ def test_long_series(self):
10561057
n = 1000
10571058
s = Series(
10581059
np.random.randint(-50, 50, n),
1059-
index=['s%04d' % x for x in range(n)], dtype='int64')
1060+
index=['s{x:04d}'.format(x=x) for x in range(n)], dtype='int64')
10601061

10611062
import re
10621063
str_rep = str(s)
@@ -1174,7 +1175,7 @@ def test_to_string(self):
11741175
assert header == expected
11751176

11761177
biggie.to_string(columns=['B', 'A'],
1177-
formatters={'A': lambda x: '%.1f' % x})
1178+
formatters={'A': lambda x: '{x:.1f}'.format(x=x)})
11781179

11791180
biggie.to_string(columns=['B', 'A'], float_format=str)
11801181
biggie.to_string(columns=['B', 'A'], col_space=12, float_format=str)
@@ -1269,7 +1270,7 @@ def test_to_string_small_float_values(self):
12691270

12701271
result = df.to_string()
12711272
# sadness per above
1272-
if '%.4g' % 1.7e8 == '1.7e+008':
1273+
if '{x:.4g}'.format(x=1.7e8) == '1.7e+008':
12731274
expected = (' a\n'
12741275
'0 1.500000e+000\n'
12751276
'1 1.000000e-017\n'
@@ -1456,7 +1457,7 @@ def test_repr_html_long(self):
14561457
long_repr = df._repr_html_()
14571458
assert '..' in long_repr
14581459
assert str(41 + max_rows // 2) not in long_repr
1459-
assert u('%d rows ') % h in long_repr
1460+
assert u('{h} rows ').format(h=h) in long_repr
14601461
assert u('2 columns') in long_repr
14611462

14621463
def test_repr_html_float(self):
@@ -1478,7 +1479,7 @@ def test_repr_html_float(self):
14781479
long_repr = df._repr_html_()
14791480
assert '..' in long_repr
14801481
assert '31' not in long_repr
1481-
assert u('%d rows ') % h in long_repr
1482+
assert u('{h} rows ').format(h=h) in long_repr
14821483
assert u('2 columns') in long_repr
14831484

14841485
def test_repr_html_long_multiindex(self):
@@ -1673,7 +1674,7 @@ def test_to_string(self):
16731674
result = cp.to_string(length=True, name=True, dtype=True)
16741675
last_line = result.split('\n')[-1].strip()
16751676
assert last_line == ("Freq: B, Name: foo, "
1676-
"Length: %d, dtype: float64" % len(cp))
1677+
"Length: {cp}, dtype: float64".format(cp=len(cp)))
16771678

16781679
def test_freq_name_separation(self):
16791680
s = Series(np.random.randn(10),
@@ -2176,7 +2177,7 @@ def test_to_string_header(self):
21762177

21772178

21782179
def _three_digit_exp():
2179-
return '%.4g' % 1.7e8 == '1.7e+008'
2180+
return '{x:.4g}'.format(x=1.7e8) == '1.7e+008'
21802181

21812182

21822183
class TestFloatArrayFormatter(object):

pandas/tests/io/formats/test_style.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ def setup_method(self, method):
2222
self.g = lambda x: x
2323

2424
def h(x, foo='bar'):
25-
return pd.Series(['color: %s' % foo], index=x.index, name=x.name)
25+
return pd.Series(
26+
['color: {foo}'.format(foo=foo)], index=x.index, name=x.name)
2627

2728
self.h = h
2829
self.styler = Styler(self.df)
@@ -214,7 +215,7 @@ def test_numeric_columns(self):
214215

215216
def test_apply_axis(self):
216217
df = pd.DataFrame({'A': [0, 0], 'B': [1, 1]})
217-
f = lambda x: ['val: %s' % x.max() for v in x]
218+
f = lambda x: ['val: {max}'.format(max=x.max()) for v in x]
218219
result = df.style.apply(f, axis=1)
219220
assert len(result._todo) == 1
220221
assert len(result.ctx) == 0
@@ -658,7 +659,8 @@ def test_highlight_max(self):
658659

659660
def test_export(self):
660661
f = lambda x: 'color: red' if x > 0 else 'color: blue'
661-
g = lambda x, y, z: 'color: %s' if x > 0 else 'color: %s' % z
662+
g = lambda x, y, z: 'color: {z}'.format(z=z) \
663+
if x > 0 else 'color: {z}'.format(z=z)
662664
style1 = self.styler
663665
style1.applymap(f)\
664666
.applymap(g, y='a', z='b')\

pandas/tests/io/formats/test_to_html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1435,7 +1435,7 @@ def test_to_html(self):
14351435

14361436
biggie.to_html(columns=['B', 'A'], col_space=17)
14371437
biggie.to_html(columns=['B', 'A'],
1438-
formatters={'A': lambda x: '%.1f' % x})
1438+
formatters={'A': lambda x: '{x:.1f}'.format(x=x)})
14391439

14401440
biggie.to_html(columns=['B', 'A'], float_format=str)
14411441
biggie.to_html(columns=['B', 'A'], col_space=12, float_format=str)

pandas/tests/io/formats/test_to_latex.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,11 @@ def test_to_latex_with_formatters(self):
9999
datetime(2016, 2, 5),
100100
datetime(2016, 3, 3)]})
101101

102-
formatters = {'int': lambda x: '0x%x' % x,
103-
'float': lambda x: '[% 4.1f]' % x,
104-
'object': lambda x: '-%s-' % str(x),
102+
formatters = {'int': lambda x: '0x{x:x}'.format(x=x),
103+
'float': lambda x: '[{x: 4.1f}]'.format(x=x),
104+
'object': lambda x: '-{x!s}-'.format(x=x),
105105
'datetime64': lambda x: x.strftime('%Y-%m'),
106-
'__index__': lambda x: 'index: %s' % x}
106+
'__index__': lambda x: 'index: {x}'.format(x=x)}
107107
result = df.to_latex(formatters=dict(formatters))
108108

109109
expected = r"""\begin{tabular}{llrrl}

pandas/tests/io/json/test_pandas.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,8 @@ def __str__(self):
531531

532532
# verify the proper conversion of printable content
533533
df_printable = DataFrame({'A': [binthing.hexed]})
534-
assert df_printable.to_json() == '{"A":{"0":"%s"}}' % hexed
534+
assert df_printable.to_json() == \
535+
'{{"A":{{"0":"{hex}"}}}}'.format(hex=hexed)
535536

536537
# check if non-printable content throws appropriate Exception
537538
df_nonprintable = DataFrame({'A': [binthing]})
@@ -546,15 +547,16 @@ def __str__(self):
546547

547548
# default_handler should resolve exceptions for non-string types
548549
assert df_nonprintable.to_json(default_handler=str) == \
549-
'{"A":{"0":"%s"}}' % hexed
550+
'{{"A":{{"0":"{hex}"}}}}'.format(hex=hexed)
550551
assert df_mixed.to_json(default_handler=str) == \
551-
'{"A":{"0":"%s"},"B":{"0":1}}' % hexed
552+
'{{"A":{{"0":"{hex}"}},"B":{{"0":1}}}}'.format(hex=hexed)
552553

553554
def test_label_overflow(self):
554555
# GH14256: buffer length not checked when writing label
555556
df = pd.DataFrame({'foo': [1337], 'bar' * 100000: [1]})
556557
assert df.to_json() == \
557-
'{"%s":{"0":1},"foo":{"0":1337}}' % ('bar' * 100000)
558+
'{{"{bar}":{{"0":1}},"foo":{{"0":1337}}}}'.format(
559+
bar=('bar' * 100000))
558560

559561
def test_series_non_unique_index(self):
560562
s = Series(['a', 'b'], index=[1, 1])

pandas/tests/io/json/test_readlines.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def test_readjson_chunks_closes(chunksize):
131131
lines=True, chunksize=chunksize, compression=None)
132132
reader.read()
133133
assert reader.open_stream.closed, "didn't close stream with \
134-
chunksize = %s" % chunksize
134+
chunksize = {chunksize}".format(chunksize=chunksize)
135135

136136

137137
@pytest.mark.parametrize("chunksize", [0, -1, 2.2, "foo"])
@@ -165,4 +165,5 @@ def test_readjson_chunks_multiple_empty_lines(chunksize):
165165
test = pd.read_json(j, lines=True, chunksize=chunksize)
166166
if chunksize is not None:
167167
test = pd.concat(test)
168-
tm.assert_frame_equal(orig, test, obj="chunksize: %s" % chunksize)
168+
tm.assert_frame_equal(
169+
orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize))

pandas/tests/io/json/test_ujson.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -394,21 +394,21 @@ def test_encodeTimeConversion(self):
394394
]
395395
for test in tests:
396396
output = ujson.encode(test)
397-
expected = '"%s"' % test.isoformat()
397+
expected = '"{iso}"'.format(iso=test.isoformat())
398398
assert expected == output
399399

400400
def test_encodeTimeConversion_pytz(self):
401401
# see gh-11473: to_json segfaults with timezone-aware datetimes
402402
test = datetime.time(10, 12, 15, 343243, pytz.utc)
403403
output = ujson.encode(test)
404-
expected = '"%s"' % test.isoformat()
404+
expected = '"{iso}"'.format(iso=test.isoformat())
405405
assert expected == output
406406

407407
def test_encodeTimeConversion_dateutil(self):
408408
# see gh-11473: to_json segfaults with timezone-aware datetimes
409409
test = datetime.time(10, 12, 15, 343243, dateutil.tz.tzutc())
410410
output = ujson.encode(test)
411-
expected = '"%s"' % test.isoformat()
411+
expected = '"{iso}"'.format(iso=test.isoformat())
412412
assert expected == output
413413

414414
def test_nat(self):
@@ -856,9 +856,9 @@ def test_decodeNumberWith32bitSignBit(self):
856856
boundary2 = 2**32 # noqa
857857
docs = (
858858
'{"id": 3590016419}',
859-
'{"id": %s}' % 2**31,
860-
'{"id": %s}' % 2**32,
861-
'{"id": %s}' % ((2**32) - 1),
859+
'{{"id": {low}}}'.format(low=2**31),
860+
'{{"id": {high}}}'.format(high=2**32),
861+
'{{"id": {one_less}}}'.format(one_less=(2**32) - 1),
862862
)
863863
results = (3590016419, 2**31, 2**32, 2**32 - 1)
864864
for doc, result in zip(docs, results):

pandas/tests/io/sas/test_sas7bdat.py

+15-9
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ def setup_method(self, method):
1515
self.data = []
1616
self.test_ix = [list(range(1, 16)), [16]]
1717
for j in 1, 2:
18-
fname = os.path.join(self.dirpath, "test_sas7bdat_%d.csv" % j)
18+
fname = os.path.join(
19+
self.dirpath, "test_sas7bdat_{j}.csv".format(j=j))
1920
df = pd.read_csv(fname)
2021
epoch = pd.datetime(1960, 1, 1)
2122
t1 = pd.to_timedelta(df["Column4"], unit='d')
@@ -37,15 +38,17 @@ def test_from_file(self):
3738
for j in 0, 1:
3839
df0 = self.data[j]
3940
for k in self.test_ix[j]:
40-
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
41+
fname = os.path.join(
42+
self.dirpath, "test{k}.sas7bdat".format(k=k))
4143
df = pd.read_sas(fname, encoding='utf-8')
4244
tm.assert_frame_equal(df, df0)
4345

4446
def test_from_buffer(self):
4547
for j in 0, 1:
4648
df0 = self.data[j]
4749
for k in self.test_ix[j]:
48-
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
50+
fname = os.path.join(
51+
self.dirpath, "test{k}.sas7bdat".format(k=k))
4952
with open(fname, 'rb') as f:
5053
byts = f.read()
5154
buf = io.BytesIO(byts)
@@ -59,7 +62,8 @@ def test_from_iterator(self):
5962
for j in 0, 1:
6063
df0 = self.data[j]
6164
for k in self.test_ix[j]:
62-
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
65+
fname = os.path.join(
66+
self.dirpath, "test{k}.sas7bdat".format(k=k))
6367
rdr = pd.read_sas(fname, iterator=True, encoding='utf-8')
6468
df = rdr.read(2)
6569
tm.assert_frame_equal(df, df0.iloc[0:2, :])
@@ -73,7 +77,8 @@ def test_path_pathlib(self):
7377
for j in 0, 1:
7478
df0 = self.data[j]
7579
for k in self.test_ix[j]:
76-
fname = Path(os.path.join(self.dirpath, "test%d.sas7bdat" % k))
80+
fname = Path(os.path.join(
81+
self.dirpath, "test{k}.sas7bdat".format(k=k)))
7782
df = pd.read_sas(fname, encoding='utf-8')
7883
tm.assert_frame_equal(df, df0)
7984

@@ -83,8 +88,8 @@ def test_path_localpath(self):
8388
for j in 0, 1:
8489
df0 = self.data[j]
8590
for k in self.test_ix[j]:
86-
fname = LocalPath(os.path.join(self.dirpath,
87-
"test%d.sas7bdat" % k))
91+
fname = LocalPath(os.path.join(
92+
self.dirpath, "test{k}.sas7bdat".format(k=k)))
8893
df = pd.read_sas(fname, encoding='utf-8')
8994
tm.assert_frame_equal(df, df0)
9095

@@ -93,7 +98,8 @@ def test_iterator_loop(self):
9398
for j in 0, 1:
9499
for k in self.test_ix[j]:
95100
for chunksize in 3, 5, 10, 11:
96-
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
101+
fname = os.path.join(
102+
self.dirpath, "test{k}.sas7bdat".format(k=k))
97103
rdr = pd.read_sas(fname, chunksize=10, encoding='utf-8')
98104
y = 0
99105
for x in rdr:
@@ -104,7 +110,7 @@ def test_iterator_loop(self):
104110
def test_iterator_read_too_much(self):
105111
# github #14734
106112
k = self.test_ix[0][0]
107-
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
113+
fname = os.path.join(self.dirpath, "test{k}.sas7bdat".format(k=k))
108114
rdr = pd.read_sas(fname, format="sas7bdat",
109115
iterator=True, encoding='utf-8')
110116
d1 = rdr.read(rdr.row_count + 20)

0 commit comments

Comments
 (0)