Formatting a regular string which could be a f-string
1632 if figfmt == "svg":
1633 return figbytes.decode()
1634 data_uri = _b64encode(figbytes).decode()
1635 embed_string = '<img src="data:image/{};base64,{}" />'.format(figfmt, data_uri)1636 return embed_string
Formatting a regular string which could be a f-string
1625 return figbytes.decode()
1626 data_uri = _b64encode(figbytes).decode()
1627 embed_string.join(
1628 '<img src="data:image/{};base64,{}" />'.format(figfmt, data_uri)1629 )
1630 else:
1631 figbytes = figfiles.getvalue()
Formatting a regular string which could be a f-string
836 if compounded:
837 metrics["Cumulative Return %"] = (_stats.comp(df) * pct).map("{:,.2f}".format)
838 else:
839 metrics["Total Return %"] = (df.sum() * pct).map("{:,.2f}".format) 840
841 metrics["CAGR﹪%"] = _stats.cagr(df, rf, compounded) * pct
842
Formatting a regular string which could be a f-string
834 metrics["~"] = blank
835
836 if compounded:
837 metrics["Cumulative Return %"] = (_stats.comp(df) * pct).map("{:,.2f}".format) 838 else:
839 metrics["Total Return %"] = (df.sum() * pct).map("{:,.2f}".format)
840
Formatting a regular string which could be a f-string
575 for ptf, dd_info in dd_info_dict.items():
576 iDisplay(
577 iHTML(
578 '<h4 style="margin-bottom:20px">%s - Worst 5 Drawdowns</h4>' 579 % ptf
580 )
581 )
Formatting a regular string which could be a f-string
143 for i in reversed(range(num_cols + 1, num_cols + 3)):
144 str_td = "<td></td>" * i
145 tpl = tpl.replace(
146 f"<tr>{str_td}</tr>", '<tr><td colspan="{}"><hr></td></tr>'.format(i) 147 )
148
149 tpl = tpl.replace(
Formatting a regular string which could be a f-string
923 hline=returns.mean(),
924 hlw=1.5,
925 ylabel=ylabel,
926 title="Rolling Sortino (%s)" % period_label, 927 fontname=fontname,
928 grayscale=grayscale,
929 lw=lw,
Formatting a regular string which could be a f-string
879 hline=returns.mean(),
880 hlw=1.5,
881 ylabel=ylabel,
882 title="Rolling Sharpe (%s)" % period_label, 883 fontname=fontname,
884 grayscale=grayscale,
885 lw=lw,
Formatting a regular string which could be a f-string
829 hline=returns.mean(),
830 hlw=1.5,
831 ylabel=ylabel,
832 title="Rolling Volatility (%s)" % period_label, 833 fontname=fontname,
834 grayscale=grayscale,
835 lw=lw,
Formatting a regular string which could be a f-string
664 resample=resample,
665 grayscale=grayscale,
666 fontname=fontname,
667 title="Distribution of %sReturns" % title, 668 figsize=figsize,
669 ylabel=ylabel,
670 subtitle=subtitle,
Formatting a regular string which could be a f-string
453 title = "Cumulative Returns" if compound else "Returns"
454 if benchmark is not None:
455 if isinstance(benchmark, str):
456 title += " vs %s (Log Scaled" % benchmark.upper() 457 else:
458 title += " vs Benchmark (Log Scaled"
459 if match_volatility:
Formatting a regular string which could be a f-string
401 title = "Cumulative Returns" if compound else "Returns"
402 if benchmark is not None:
403 if isinstance(benchmark, str):
404 title += " vs %s" % benchmark.upper() 405 else:
406 title += " vs Benchmark"
407 if match_volatility:
Formatting a regular string which could be a f-string
342 ax.plot(returns.index, returns, color=colors[1], lw=1 if grayscale else lw)
343
344 ax.set_ylabel(
345 "Value of ${:,.0f}".format(start_balance), 346 fontname=fontname,
347 fontweight="bold",
348 fontsize=12,
Formatting a regular string which could be a f-string
316 "${:,}".format(round(returns.values[-1] - returns.values[0], 2))
317 ),
318 _utils._score_str(
319 "{:,}%".format( 320 round((returns.values[-1] / returns.values[0] - 1) * 100, 2)
321 )
322 ),
Formatting a regular string which could be a f-string
313 returns.index.date[1:2][0].strftime("%e %b '%y"),
314 returns.index.date[-1:][0].strftime("%e %b '%y"),
315 _utils._score_str(
316 "${:,}".format(round(returns.values[-1] - returns.values[0], 2)) 317 ),
318 _utils._score_str(
319 "{:,}%".format(
Formatting a regular string which could be a f-string
308
309 if subtitle:
310 ax.set_title(
311 "\n%s - %s ; P&L: %s (%s) " 312 % (
313 returns.index.date[1:2][0].strftime("%e %b '%y"),
314 returns.index.date[-1:][0].strftime("%e %b '%y"),
Formatting a regular string which could be a f-string
139 )
140 elif isinstance(returns, _pd.DataFrame):
141 axes[0].set_title(
142 "\n%s - %s ; " 143 % (
144 returns.index.date[:1][0].strftime("%e %b '%y"),
145 returns.index.date[-1:][0].strftime("%e %b '%y"),
Formatting a regular string which could be a f-string
128 if subtitle:
129 if isinstance(returns, _pd.Series):
130 axes[0].set_title(
131 "%s - %s ; Sharpe: %.2f \n" 132 % (
133 returns.index.date[:1][0].strftime("%e %b '%y"),
134 returns.index.date[-1:][0].strftime("%e %b '%y"),
Formatting a regular string which could be a f-string
1223 if x >= 1e3:
1224 res = "%1.1fK%%" % (x * 1e-3)
1225 return res.replace(".0K%", "K%")
1226 res = "%1.0f%%" % x1227 return res.replace(".0%", "%")
Formatting a regular string which could be a f-string
1221 res = "%1.1fM%%" % (x * 1e-6)
1222 return res.replace(".0M%", "M%")
1223 if x >= 1e3:
1224 res = "%1.1fK%%" % (x * 1e-3)1225 return res.replace(".0K%", "K%")
1226 res = "%1.0f%%" % x
1227 return res.replace(".0%", "%")
Formatting a regular string which could be a f-string
1218 res = "%1.1fB%%" % (x * 1e-9)
1219 return res.replace(".0B%", "B%")
1220 if x >= 1e6:
1221 res = "%1.1fM%%" % (x * 1e-6)1222 return res.replace(".0M%", "M%")
1223 if x >= 1e3:
1224 res = "%1.1fK%%" % (x * 1e-3)
Formatting a regular string which could be a f-string
1215 res = "%1.1fT%%" % (x * 1e-12)
1216 return res.replace(".0T%", "T%")
1217 if x >= 1e9:
1218 res = "%1.1fB%%" % (x * 1e-9)1219 return res.replace(".0B%", "B%")
1220 if x >= 1e6:
1221 res = "%1.1fM%%" % (x * 1e-6)
Formatting a regular string which could be a f-string
1212def format_pct_axis(x, _):
1213 x *= 100 # lambda x, loc: "{:,}%".format(int(x * 100))
1214 if x >= 1e12:
1215 res = "%1.1fT%%" % (x * 1e-12)1216 return res.replace(".0T%", "T%")
1217 if x >= 1e9:
1218 res = "%1.1fB%%" % (x * 1e-9)
Formatting a regular string which could be a f-string
1205 if x >= 1e3:
1206 res = "$%1.0fK" % (x * 1e-3)
1207 return res.replace(".0K", "K")
1208 res = "$%1.0f" % x1209 return res.replace(".0", "")
1210
1211
Formatting a regular string which could be a f-string
1203 res = "$%1.1fM" % (x * 1e-6)
1204 return res.replace(".0M", "M")
1205 if x >= 1e3:
1206 res = "$%1.0fK" % (x * 1e-3)1207 return res.replace(".0K", "K")
1208 res = "$%1.0f" % x
1209 return res.replace(".0", "")
Description
f-strings are the fastest way to format strings as compared to the following methods:
- using format specifiers
%
- using
format()
- using
str.join
- using
+
operator to concatinate string - using
Template.substitute
Bad practice
Some less preferred ways to format strings are the following:
from string import Template
menu = ('eggs', 'spam', 42.4)
old_order = "%s and %s: %.2f ¤" % menu # [consider-using-f-string]
beginner_order = menu[0] + " and " + menu[1] + ": " + str(menu[2]) + " ¤"
joined_order = " and ".join(menu[:2])
format_order = "{} and {}: {:0.2f} ¤".format(menu[0], menu[1], menu[2])
named_format_order = "{eggs} and {spam}: {price:0.2f} ¤".format(eggs=menu[0], spam=menu[1], price=menu[2])
template_order = Template('$eggs and $spam: $price ¤').substitute(eggs=menu[0], spam=menu[1], price=menu[2])
Recommended
Consider using f-strings as shown below:
menu = ('eggs', 'spam', 42.4)
f_string_order = f"{menu[0]} and {menu[1]}: {menu[2]:0.2f} ¤"