Sometimes you are given the opportunity to customize a printf-style format string which is used to output something. You have no control, however, on how it is used. Your format string must include as many placeholders as the number of values the %
operator is used with. Otherwise, you get a TypeError: “not all arguments converted during string formatting”.
Then, how to discard a value? From reading the documentation, there is apparently no conversion type specifically for that.
For instance, let’s say I use the library function defined below, but I am not interested in the number 42 and just want to print “Hello world”.
def some_library_function(fmt):
print(fmt % 42)
Use %.0s
.
some_library_function('Hello world%.0s')
# prints: 'Hello world'
Explanation: .0
specifies a precision of zero, which for s
trings is interpreted as the maximal number of characters to include in the result. So the value passed to %
is converted to a string using str()
, then this string is truncated to length zero.