Formatting a regular string which could be a f-string
147 typeTag = ''
148
149 timestamp = time.strftime("%d/%m/%Y %H:%M:%S")
150 return "%s :: %s%s" % (timestamp, typeTag, message)151
152
153logToDir = carbonLogObserver.log_to_dir
Formatting a regular string which could be a f-string
142 message = textFromEventDict(event)
143
144 if includeType:
145 typeTag = '[%s] ' % event.get('type', 'console')146 else:
147 typeTag = ''
148
Formatting a regular string which could be a f-string
21 """
22 openMode = self.defaultMode or 0o777
23 # Fix >= Python3.8 raises RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode # NOQA
24 python_version = '%s.%s.%s' % (str(version_info[0]), str(version_info[1]), str(version_info[2])) 25 use_buffering = 0
26 if python_version < '3.8.0':
27 use_buffering = 1
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} ¤"