1

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)
6
  • Why are you using a function that outputs 42 if you don't want 42 to be output? Commented Apr 30, 2021 at 13:57
  • Of course this is a minimal example… In a more realistic setting you may use a function / library / program which does more interesting things, and which happens to print things (but is not a mere proxy to print!), and you want to customize what is printed. Commented Apr 30, 2021 at 13:59
  • How does that work if, again, you do not control the code that performs interpolation? Commented Apr 30, 2021 at 14:14
  • “Artificial restriction“ how so! Not being in control of the API/interface/call-it-however-you-like of libraries/software you rely on is, I believe, a fairly typical situation? But if you want a specific (irrelevant to the general question) example: the footnotes extension to Python-Markdown adds supports for footnotes in a Markdown parser. It inserts backlinks whose text, by default, is Jump back to footnote %d in the text. You can change this text, but as you can see, it is a printf-style format, and it expects one integer value. Commented Apr 30, 2021 at 14:39
  • Anyway, I don’t see the point in challenging the why if not for providing an helpful answer to the how. Commented Apr 30, 2021 at 14:41

1 Answer 1

1

Use %.0s.

some_library_function('Hello world%.0s')
# prints: 'Hello world'

Explanation: .0 specifies a precision of zero, which for strings 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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you had included this example in your question, it would have made your question much clearer.
I… did? -------

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.