String formatting expressions:
'This is %d %s example!' % (1, 'nice')
String formatting method calls:
'This is {0} {1} example!'.format(1, 'nice')
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. custom_string = "String formatting" print(f"{custom_string} is a powerful technique") String formatting is a powerful technique.
%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))
The __format__() method is used by string. format() as well as the format() built-in function. Both of these interfaces are used to get presentable string versions of a given object.
Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict
based formatting:
d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d
It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With