I will accept @Jean-François Fabre 's answer that basically answers my question as I specified it by saying that (at least for now) there is no answer to this
using only string formatting (i.e. if the variables to be formated are just h, m & w without additional processing).
However, using the concept of boolean operators on strings as in his answer i think i will use:
print("{}{}{} {}".format(h,m and " " ,m , w))
This has the disadvantage of giving the the person reading it the feeling that 4 values are being formated (which is the case technically but not semantically) but I do think that the shortness and simplicity of the expressions here overcome the negative aspect.
Readability could be yet improved by using Parametrized formats as suggested by @Tsingyi but using the following:
print("{}{pad}{} {}".format(h, m , w, pad = m and " "))
NOTE:
THE FOLLOWING IS NOT WORKING CODE AT THE TIME OF WRITING:
Hopefully in the future maybe we could do something like:
print("{}{: >?} {}".format(h,m,w))
with the semantics of "optionally (if m then) align it to the right and pad with one additional space to its left", or
print("{} {: <?}{}".format(h,m,w))
with the semantics of "optionally (if m then) align it to the left and pad with one additional space to its right"
similar variants might be helpful for optional formatting of currency symbols
e.g.
print("{:$>?}{}".format(s))
to yield either an empty string or $123
One final (long) note:
at some point during my research of this issue I thought that I might be able to do something like this:
def extend_string_formatting():
try:
'{:left-pad-if-not-empty}'.format('')
except ValueError:
original_formatter=str.__format__
def extended_formatter(self, format):
if (format == 'left-pad-if-not-empty'):
return ' ' + self if self else ''
return original_formatter(self, format)
str.__format__=extended_formatter
extend_string_formatting()
but it turns out that this results with:
Traceback (most recent call last):
File "<input>", line 3, in extend_string_formatting
ValueError: Invalid format specifier
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 12, in extend_string_formatting
TypeError: can't set attributes of built-in/extension type 'str'
maybe this can be achieved using something like what is described here:
https://stackoverflow.com/a/15975791/25412