What's the difference between these 2 string format statements in Python:
'{0}'.format(a) '{0!s}'.format(a)
Both have the same output if a
is an integer, list or dictionary. Is the first one {0}
doing an implicit str()
call?
Source
PS: keywords: exclamation / bang "!s" formatting
%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.
Python string class gives us an important built-in command called format() that helps us to replace, substitute, or convert the string with placeholders with valid values in the final string.
The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string. It is safe to call this function with a value of “None” (because the “None” value in Python is an object and can have methods.)
It is mentioned in the documentation:
The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the
__format__()
method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling__format__()
, the normal formatting logic is bypassed.Two conversion flags are currently supported: '
!s
' which callsstr()
on the value, and '!r
' which callsrepr()
.
An example can be taken (again from the documentation) to show the difference:
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"
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