47
47
48
48
import itertools
49
49
import csv
50
+ from functools import partial
50
51
51
52
common_docstring = """
52
53
Parameters
@@ -109,7 +110,7 @@ def _get_footer(self):
109
110
if self .length :
110
111
if footer :
111
112
footer += ', '
112
- footer += "Length: %d" % len (self .categorical )
113
+ footer += "Length: {length}" . format ( length = len (self .categorical ) )
113
114
114
115
level_info = self .categorical ._repr_categories_info ()
115
116
@@ -135,7 +136,7 @@ def to_string(self):
135
136
136
137
fmt_values = self ._get_formatted_values ()
137
138
138
- result = ['%s' % i for i in fmt_values ]
139
+ result = [u ( '{i}' ). format ( i = i ) for i in fmt_values ]
139
140
result = [i .strip () for i in result ]
140
141
result = u (', ' ).join (result )
141
142
result = [u ('[' ) + result + u (']' )]
@@ -191,28 +192,29 @@ def _get_footer(self):
191
192
footer = u ('' )
192
193
193
194
if getattr (self .series .index , 'freq' , None ) is not None :
194
- footer += 'Freq: %s' % self .series .index .freqstr
195
+ footer += 'Freq: {freq}' . format ( freq = self .series .index .freqstr )
195
196
196
197
if self .name is not False and name is not None :
197
198
if footer :
198
199
footer += ', '
199
200
200
201
series_name = pprint_thing (name ,
201
202
escape_chars = ('\t ' , '\r ' , '\n ' ))
202
- footer += ("Name: %s" % series_name ) if name is not None else ""
203
+ footer += ((u"Name: {sname}" .format (sname = series_name ))
204
+ if name is not None else "" )
203
205
204
206
if (self .length is True or
205
207
(self .length == 'truncate' and self .truncate_v )):
206
208
if footer :
207
209
footer += ', '
208
- footer += 'Length: %d' % len (self .series )
210
+ footer += 'Length: {length}' . format ( length = len (self .series ) )
209
211
210
212
if self .dtype is not False and self .dtype is not None :
211
213
name = getattr (self .tr_series .dtype , 'name' , None )
212
214
if name :
213
215
if footer :
214
216
footer += ', '
215
- footer += 'dtype: %s' % pprint_thing (name )
217
+ footer += u 'dtype: {typ}' . format ( typ = pprint_thing (name ) )
216
218
217
219
# level infos are added to the end and in a new line, like it is done
218
220
# for Categoricals
@@ -509,8 +511,10 @@ def _to_str_columns(self):
509
511
else :
510
512
if is_list_like (self .header ):
511
513
if len (self .header ) != len (self .columns ):
512
- raise ValueError (('Writing %d cols but got %d aliases'
513
- % (len (self .columns ), len (self .header ))))
514
+ raise ValueError (('Writing {ncols} cols but got {nalias} '
515
+ 'aliases'
516
+ .format (ncols = len (self .columns ),
517
+ nalias = len (self .header ))))
514
518
str_columns = [[label ] for label in self .header ]
515
519
else :
516
520
str_columns = self ._get_formatted_column_labels (frame )
@@ -578,10 +582,10 @@ def to_string(self):
578
582
frame = self .frame
579
583
580
584
if len (frame .columns ) == 0 or len (frame .index ) == 0 :
581
- info_line = (u ('Empty %s \n Columns: %s \n Index: %s' ) %
582
- ( type (self .frame ).__name__ ,
583
- pprint_thing (frame .columns ),
584
- pprint_thing (frame .index )))
585
+ info_line = (u ('Empty {name} \n Columns: {col} \n Index: {idx}' )
586
+ . format ( name = type (self .frame ).__name__ ,
587
+ col = pprint_thing (frame .columns ),
588
+ idx = pprint_thing (frame .index )))
585
589
text = info_line
586
590
else :
587
591
@@ -630,8 +634,8 @@ def to_string(self):
630
634
self .buf .writelines (text )
631
635
632
636
if self .should_show_dimensions :
633
- self .buf .write ("\n \n [%d rows x %d columns]" %
634
- ( len (frame ), len (frame .columns )))
637
+ self .buf .write ("\n \n [{nrows} rows x {ncols} columns]"
638
+ . format ( nrows = len (frame ), ncols = len (frame .columns )))
635
639
636
640
def _join_multiline (self , * strcols ):
637
641
lwidth = self .line_width
@@ -805,7 +809,8 @@ def _get_formatted_index(self, frame):
805
809
806
810
# empty space for columns
807
811
if show_col_names :
808
- col_header = ['%s' % x for x in self ._get_column_name_list ()]
812
+ col_header = ['{x}' .format (x = x )
813
+ for x in self ._get_column_name_list ()]
809
814
else :
810
815
col_header = ['' ] * columns .nlevels
811
816
@@ -861,9 +866,10 @@ def write_result(self, buf):
861
866
862
867
# string representation of the columns
863
868
if len (self .frame .columns ) == 0 or len (self .frame .index ) == 0 :
864
- info_line = (u ('Empty %s\n Columns: %s\n Index: %s' ) %
865
- (type (self .frame ).__name__ , self .frame .columns ,
866
- self .frame .index ))
869
+ info_line = (u ('Empty {name}\n Columns: {col}\n Index: {idx}' )
870
+ .format (name = type (self .frame ).__name__ ,
871
+ col = self .frame .columns ,
872
+ idx = self .frame .index ))
867
873
strcols = [[info_line ]]
868
874
else :
869
875
strcols = self .fmt ._to_str_columns ()
@@ -906,14 +912,16 @@ def get_col_type(dtype):
906
912
column_format = index_format + column_format
907
913
elif not isinstance (column_format ,
908
914
compat .string_types ): # pragma: no cover
909
- raise AssertionError ('column_format must be str or unicode, not %s '
910
- % type (column_format ))
915
+ raise AssertionError ('column_format must be str or unicode, '
916
+ 'not {typ}' . format ( typ = type (column_format ) ))
911
917
912
918
if not self .longtable :
913
- buf .write ('\\ begin{tabular}{%s}\n ' % column_format )
919
+ buf .write ('\\ begin{{tabular}}{{{fmt}}}\n '
920
+ .format (fmt = column_format ))
914
921
buf .write ('\\ toprule\n ' )
915
922
else :
916
- buf .write ('\\ begin{longtable}{%s}\n ' % column_format )
923
+ buf .write ('\\ begin{{longtable}}{{{fmt}}}\n '
924
+ .format (fmt = column_format ))
917
925
buf .write ('\\ toprule\n ' )
918
926
919
927
ilevels = self .frame .index .nlevels
@@ -948,7 +956,7 @@ def get_col_type(dtype):
948
956
crow = [x if x else '{}' for x in row ]
949
957
if self .bold_rows and self .fmt .index :
950
958
# bold row labels
951
- crow = ['\\ textbf{%s}' % x
959
+ crow = ['\\ textbf{{{x}}}' . format ( x = x )
952
960
if j < ilevels and x .strip () not in ['' , '{}' ] else x
953
961
for j , x in enumerate (crow )]
954
962
if i < clevels and self .fmt .header and self .multicolumn :
@@ -986,9 +994,9 @@ def _format_multicolumn(self, row, ilevels):
986
994
def append_col ():
987
995
# write multicolumn if needed
988
996
if ncol > 1 :
989
- row2 .append ('\\ multicolumn{{{0 :d}}}{{{1 :s}}}{{{2 :s}}}'
990
- .format (ncol , self .multicolumn_format ,
991
- coltext .strip ()))
997
+ row2 .append ('\\ multicolumn{{{ncol :d}}}{{{fmt :s}}}{{{txt :s}}}'
998
+ .format (ncol = ncol , fmt = self .multicolumn_format ,
999
+ txt = coltext .strip ()))
992
1000
# don't modify where not needed
993
1001
else :
994
1002
row2 .append (coltext )
@@ -1027,8 +1035,8 @@ def _format_multirow(self, row, ilevels, i, rows):
1027
1035
break
1028
1036
if nrow > 1 :
1029
1037
# overwrite non-multirow entry
1030
- row [j ] = '\\ multirow{{{0 :d}}}{{*}}{{{1 :s}}}' .format (
1031
- nrow , row [j ].strip ())
1038
+ row [j ] = '\\ multirow{{{nrow :d}}}{{*}}{{{row :s}}}' .format (
1039
+ nrow = nrow , row = row [j ].strip ())
1032
1040
# save when to end the current block with \cline
1033
1041
self .clinebuf .append ([i + nrow - 1 , j + 1 ])
1034
1042
return row
@@ -1039,7 +1047,8 @@ def _print_cline(self, buf, i, icol):
1039
1047
"""
1040
1048
for cl in self .clinebuf :
1041
1049
if cl [0 ] == i :
1042
- buf .write ('\cline{{{0:d}-{1:d}}}\n ' .format (cl [1 ], icol ))
1050
+ buf .write ('\cline{{{cl:d}-{icol:d}}}\n '
1051
+ .format (cl = cl [1 ], icol = icol ))
1043
1052
# remove entries that have been written to buffer
1044
1053
self .clinebuf = [x for x in self .clinebuf if x [0 ] != i ]
1045
1054
@@ -1076,7 +1085,8 @@ def write(self, s, indent=0):
1076
1085
def write_th (self , s , indent = 0 , tags = None ):
1077
1086
if self .fmt .col_space is not None and self .fmt .col_space > 0 :
1078
1087
tags = (tags or "" )
1079
- tags += 'style="min-width: %s;"' % self .fmt .col_space
1088
+ tags += ('style="min-width: {colspace};"'
1089
+ .format (colspace = self .fmt .col_space ))
1080
1090
1081
1091
return self ._write_cell (s , kind = 'th' , indent = indent , tags = tags )
1082
1092
@@ -1085,9 +1095,9 @@ def write_td(self, s, indent=0, tags=None):
1085
1095
1086
1096
def _write_cell (self , s , kind = 'td' , indent = 0 , tags = None ):
1087
1097
if tags is not None :
1088
- start_tag = '<%s %s>' % (kind , tags )
1098
+ start_tag = '<{kind} {tags}>' . format (kind = kind , tags = tags )
1089
1099
else :
1090
- start_tag = '<%s>' % kind
1100
+ start_tag = '<{kind}>' . format ( kind = kind )
1091
1101
1092
1102
if self .escape :
1093
1103
# escape & first to prevent double escaping of &
@@ -1096,7 +1106,8 @@ def _write_cell(self, s, kind='td', indent=0, tags=None):
1096
1106
else :
1097
1107
esc = {}
1098
1108
rs = pprint_thing (s , escape_chars = esc ).strip ()
1099
- self .write ('%s%s</%s>' % (start_tag , rs , kind ), indent )
1109
+ self .write (u'{start}{rs}</{kind}>'
1110
+ .format (start = start_tag , rs = rs , kind = kind ), indent )
1100
1111
1101
1112
def write_tr (self , line , indent = 0 , indent_delta = 4 , header = False ,
1102
1113
align = None , tags = None , nindex_levels = 0 ):
@@ -1106,7 +1117,8 @@ def write_tr(self, line, indent=0, indent_delta=4, header=False,
1106
1117
if align is None :
1107
1118
self .write ('<tr>' , indent )
1108
1119
else :
1109
- self .write ('<tr style="text-align: %s;">' % align , indent )
1120
+ self .write ('<tr style="text-align: {align};">'
1121
+ .format (align = align ), indent )
1110
1122
indent += indent_delta
1111
1123
1112
1124
for i , s in enumerate (line ):
@@ -1146,8 +1158,8 @@ def write_result(self, buf):
1146
1158
if isinstance (self .classes , str ):
1147
1159
self .classes = self .classes .split ()
1148
1160
if not isinstance (self .classes , (list , tuple )):
1149
- raise AssertionError ('classes must be list or tuple, '
1150
- 'not %s' % type (self .classes ))
1161
+ raise AssertionError ('classes must be list or tuple, not {typ} '
1162
+ . format ( typ = type (self .classes ) ))
1151
1163
_classes .extend (self .classes )
1152
1164
1153
1165
if self .notebook :
@@ -1159,12 +1171,11 @@ def write_result(self, buf):
1159
1171
except (ImportError , AttributeError ):
1160
1172
pass
1161
1173
1162
- self .write ('<div{0 }>' .format (div_style ))
1174
+ self .write ('<div{style }>' .format (style = div_style ))
1163
1175
1164
1176
self .write_style ()
1165
- self .write ('<table border="%s" class="%s">' % (self .border ,
1166
- ' ' .join (_classes )),
1167
- indent )
1177
+ self .write ('<table border="{border}" class="{cls}">'
1178
+ .format (border = self .border , cls = ' ' .join (_classes )), indent )
1168
1179
1169
1180
indent += self .indent_delta
1170
1181
indent = self ._write_header (indent )
@@ -1173,8 +1184,10 @@ def write_result(self, buf):
1173
1184
self .write ('</table>' , indent )
1174
1185
if self .should_show_dimensions :
1175
1186
by = chr (215 ) if compat .PY3 else unichr (215 ) # ×
1176
- self .write (u ('<p>%d rows %s %d columns</p>' ) %
1177
- (len (frame ), by , len (frame .columns )))
1187
+ self .write (u ('<p>{rows} rows {by} {cols} columns</p>' )
1188
+ .format (rows = len (frame ),
1189
+ by = by ,
1190
+ cols = len (frame .columns )))
1178
1191
1179
1192
if self .notebook :
1180
1193
self .write ('</div>' )
@@ -1199,7 +1212,7 @@ def _column_header():
1199
1212
row .append (single_column_table (self .columns .names ))
1200
1213
else :
1201
1214
row .append ('' )
1202
- style = "text-align: %s;" % self .fmt .justify
1215
+ style = "text-align: {just};" . format ( just = self .fmt .justify )
1203
1216
row .extend ([single_column_table (c , self .fmt .justify , style )
1204
1217
for c in self .columns ])
1205
1218
else :
@@ -1214,7 +1227,7 @@ def _column_header():
1214
1227
indent += self .indent_delta
1215
1228
1216
1229
if isinstance (self .columns , MultiIndex ):
1217
- template = 'colspan="%d " halign="left"'
1230
+ template = 'colspan="{span:d} " halign="left"'
1218
1231
1219
1232
if self .fmt .sparsify :
1220
1233
# GH3547
@@ -1282,7 +1295,7 @@ def _column_header():
1282
1295
for i , v in enumerate (values ):
1283
1296
if i in records :
1284
1297
if records [i ] > 1 :
1285
- tags [j ] = template % records [i ]
1298
+ tags [j ] = template . format ( span = records [i ])
1286
1299
else :
1287
1300
continue
1288
1301
j += 1
@@ -1372,7 +1385,7 @@ def _write_regular_rows(self, fmt_values, indent):
1372
1385
nindex_levels = 1 )
1373
1386
1374
1387
def _write_hierarchical_rows (self , fmt_values , indent ):
1375
- template = 'rowspan="%d " valign="top"'
1388
+ template = 'rowspan="{span} " valign="top"'
1376
1389
1377
1390
truncate_h = self .fmt .truncate_h
1378
1391
truncate_v = self .fmt .truncate_v
@@ -1447,7 +1460,7 @@ def _write_hierarchical_rows(self, fmt_values, indent):
1447
1460
for records , v in zip (level_lengths , idx_values [i ]):
1448
1461
if i in records :
1449
1462
if records [i ] > 1 :
1450
- tags [j ] = template % records [i ]
1463
+ tags [j ] = template . format ( span = records [i ])
1451
1464
else :
1452
1465
sparse_offset += 1
1453
1466
continue
@@ -1615,8 +1628,9 @@ def _save_header(self):
1615
1628
return
1616
1629
if has_aliases :
1617
1630
if len (header ) != len (cols ):
1618
- raise ValueError (('Writing %d cols but got %d aliases'
1619
- % (len (cols ), len (header ))))
1631
+ raise ValueError (('Writing {ncols} cols but got {nalias} '
1632
+ 'aliases' .format (ncols = len (cols ),
1633
+ nalias = len (header ))))
1620
1634
else :
1621
1635
write_cols = header
1622
1636
else :
@@ -1790,8 +1804,9 @@ def _format_strings(self):
1790
1804
if self .float_format is None :
1791
1805
float_format = get_option ("display.float_format" )
1792
1806
if float_format is None :
1793
- fmt_str = '%% .%dg' % get_option ("display.precision" )
1794
- float_format = lambda x : fmt_str % x
1807
+ fmt_str = ('{{x: .{prec:d}g}}'
1808
+ .format (prec = get_option ("display.precision" )))
1809
+ float_format = lambda x : fmt_str .format (x = x )
1795
1810
else :
1796
1811
float_format = self .float_format
1797
1812
@@ -1807,10 +1822,10 @@ def _format(x):
1807
1822
return 'NaT'
1808
1823
return self .na_rep
1809
1824
elif isinstance (x , PandasObject ):
1810
- return '%s' % x
1825
+ return u'{x}' . format ( x = x )
1811
1826
else :
1812
1827
# object dtype
1813
- return '%s' % formatter (x )
1828
+ return u'{x}' . format ( x = formatter (x ) )
1814
1829
1815
1830
vals = self .values
1816
1831
if isinstance (vals , Index ):
@@ -1824,11 +1839,11 @@ def _format(x):
1824
1839
fmt_values = []
1825
1840
for i , v in enumerate (vals ):
1826
1841
if not is_float_type [i ] and leading_space :
1827
- fmt_values .append (' %s' % _format (v ))
1842
+ fmt_values .append (u' {v}' . format ( v = _format (v ) ))
1828
1843
elif is_float_type [i ]:
1829
1844
fmt_values .append (float_format (v ))
1830
1845
else :
1831
- fmt_values .append (' %s' % _format (v ))
1846
+ fmt_values .append (u' {v}' . format ( v = _format (v ) ))
1832
1847
1833
1848
return fmt_values
1834
1849
@@ -1864,7 +1879,7 @@ def _value_formatter(self, float_format=None, threshold=None):
1864
1879
# because str(0.0) = '0.0' while '%g' % 0.0 = '0'
1865
1880
if float_format :
1866
1881
def base_formatter (v ):
1867
- return ( float_format % v ) if notna (v ) else self .na_rep
1882
+ return float_format ( value = v ) if notna (v ) else self .na_rep
1868
1883
else :
1869
1884
def base_formatter (v ):
1870
1885
return str (v ) if notna (v ) else self .na_rep
@@ -1925,10 +1940,14 @@ def format_values_with(float_format):
1925
1940
1926
1941
# There is a special default string when we are fixed-width
1927
1942
# The default is otherwise to use str instead of a formatting string
1928
- if self .float_format is None and self .fixed_width :
1929
- float_format = '%% .%df' % self .digits
1943
+ if self .float_format is None :
1944
+ if self .fixed_width :
1945
+ float_format = partial ('{value: .{digits:d}f}' .format ,
1946
+ digits = self .digits )
1947
+ else :
1948
+ float_format = self .float_format
1930
1949
else :
1931
- float_format = self .float_format
1950
+ float_format = lambda value : self .float_format % value
1932
1951
1933
1952
formatted_values = format_values_with (float_format )
1934
1953
@@ -1955,7 +1974,8 @@ def format_values_with(float_format):
1955
1974
(abs_vals > 0 )).any ()
1956
1975
1957
1976
if has_small_values or (too_long and has_large_values ):
1958
- float_format = '%% .%de' % self .digits
1977
+ float_format = partial ('{value: .{digits:d}e}' .format ,
1978
+ digits = self .digits )
1959
1979
formatted_values = format_values_with (float_format )
1960
1980
1961
1981
return formatted_values
@@ -1971,7 +1991,7 @@ def _format_strings(self):
1971
1991
class IntArrayFormatter (GenericArrayFormatter ):
1972
1992
1973
1993
def _format_strings (self ):
1974
- formatter = self .formatter or (lambda x : '% d' % x )
1994
+ formatter = self .formatter or (lambda x : '{x: d}' . format ( x = x ) )
1975
1995
fmt_values = [formatter (x ) for x in self .values ]
1976
1996
return fmt_values
1977
1997
@@ -2023,7 +2043,7 @@ def _format_strings(self):
2023
2043
# periods may contains different freq
2024
2044
values = Index (self .values , dtype = 'object' ).to_native_types ()
2025
2045
2026
- formatter = self .formatter or (lambda x : '%s' % x )
2046
+ formatter = self .formatter or (lambda x : '{x}' . format ( x = x ) )
2027
2047
fmt_values = [formatter (x ) for x in values ]
2028
2048
return fmt_values
2029
2049
@@ -2223,7 +2243,7 @@ def _formatter(x):
2223
2243
x = Timedelta (x )
2224
2244
result = x ._repr_base (format = format )
2225
2245
if box :
2226
- result = "'{0 }'" .format (result )
2246
+ result = "'{res }'" .format (res = result )
2227
2247
return result
2228
2248
2229
2249
return _formatter
@@ -2278,20 +2298,20 @@ def _cond(values):
2278
2298
def single_column_table (column , align = None , style = None ):
2279
2299
table = '<table'
2280
2300
if align is not None :
2281
- table += (' align="%s"' % align )
2301
+ table += (' align="{align}"' . format ( align = align ) )
2282
2302
if style is not None :
2283
- table += (' style="%s"' % style )
2303
+ table += (' style="{style}"' . format ( style = style ) )
2284
2304
table += '><tbody>'
2285
2305
for i in column :
2286
- table += ('<tr><td>%s </td></tr>' % str ( i ))
2306
+ table += ('<tr><td>{i!s} </td></tr>' . format ( i = i ))
2287
2307
table += '</tbody></table>'
2288
2308
return table
2289
2309
2290
2310
2291
2311
def single_row_table (row ): # pragma: no cover
2292
2312
table = '<table><tbody><tr>'
2293
2313
for i in row :
2294
- table += ('<td>%s </td>' % str ( i ))
2314
+ table += ('<td>{i!s} </td>' . format ( i = i ))
2295
2315
table += '</tr></tbody></table>'
2296
2316
return table
2297
2317
@@ -2385,18 +2405,19 @@ def __call__(self, num):
2385
2405
prefix = self .ENG_PREFIXES [int_pow10 ]
2386
2406
else :
2387
2407
if int_pow10 < 0 :
2388
- prefix = 'E-% 02d' % ( - int_pow10 )
2408
+ prefix = 'E-{pow10: 02d}' . format ( pow10 = - int_pow10 )
2389
2409
else :
2390
- prefix = 'E+% 02d' % int_pow10
2410
+ prefix = 'E+{pow10: 02d}' . format ( pow10 = int_pow10 )
2391
2411
2392
2412
mant = sign * dnum / (10 ** pow10 )
2393
2413
2394
2414
if self .accuracy is None : # pragma: no cover
2395
- format_str = u ("% g%s " )
2415
+ format_str = u ("{mant: g}{prefix} " )
2396
2416
else :
2397
- format_str = (u ("%% .%if%%s" ) % self .accuracy )
2417
+ format_str = (u ("{{mant: .{acc:d}f}}{{prefix}}" )
2418
+ .format (acc = self .accuracy ))
2398
2419
2399
- formatted = format_str % (mant , prefix )
2420
+ formatted = format_str . format (mant = mant , prefix = prefix )
2400
2421
2401
2422
return formatted # .strip()
2402
2423
0 commit comments