Formatting a regular string which could be a f-string
50 raise ValueError('Invalid dampening value: {}'.format(dampening))
51 if weight_decay < 0.0:
52 raise ValueError(
53 'Invalid weight_decay value: {}'.format(weight_decay) 54 )
55
56 defaults = dict(
Formatting a regular string which could be a f-string
47 if momentum < 0.0:
48 raise ValueError('Invalid momentum value: {}'.format(momentum))
49 if dampening < 0.0:
50 raise ValueError('Invalid dampening value: {}'.format(dampening)) 51 if weight_decay < 0.0:
52 raise ValueError(
53 'Invalid weight_decay value: {}'.format(weight_decay)
Formatting a regular string which could be a f-string
45 if lr <= 0.0:
46 raise ValueError('Invalid learning rate: {}'.format(lr))
47 if momentum < 0.0:
48 raise ValueError('Invalid momentum value: {}'.format(momentum)) 49 if dampening < 0.0:
50 raise ValueError('Invalid dampening value: {}'.format(dampening))
51 if weight_decay < 0.0:
Formatting a regular string which could be a f-string
43 nesterov: bool = False,
44 ) -> None:
45 if lr <= 0.0:
46 raise ValueError('Invalid learning rate: {}'.format(lr)) 47 if momentum < 0.0:
48 raise ValueError('Invalid momentum value: {}'.format(momentum))
49 if dampening < 0.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} ¤"