I agree with @ Jean-François Fabre's answer, which basically answers my question, as I pointed it out, saying that (at least for now) there is no answer to this question using only string formatting (i.e. if the generated variables are only h, m and w without additional processing).
However, using the concept of Boolean operators in strings, as in his answer, I think I will use:
print("{}{}{} {}".format(h,m and " " ,m , w))
This drawback is that a person reads this feeling that 4 meanings are being formed (which takes place technically, but not semantically), but I think that briefly and simplicity of expression overcomes the negative aspect.
Readability can be improved using parameterized formats, as suggested by @Tsingyi, but using the following:
print("{}{pad}{} {}".format(h, m , w, pad = m and " "))
Note:
NEXT NON-OPERATING CODE DURING LETTERS:
Hopefully in the future, maybe we could do something like:
print("{}{: >?} {}".format(h,m,w))
with semantics "optionally (if m then) align it to the right and the area with one additional space on the left" or
print("{} {: <?}{}".format(h,m,w))
with semantics "optionally (if m then) align it to the left and the site with one additional space to the right"
similar options may be useful for optional formatting currency symbols for example.
print("{:$>?}{}".format(s))
to get either an empty string or $ 123
One final (long) note: at some point during my research on this problem, I thought that I could 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 leads to:
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'
Perhaps this can be achieved with something like the one described here: https://stackoverflow.com/a/212618/