我会接受@Jean-François Fabre 的回答,它基本上回答了我的问题,因为我说(至少目前)没有答案
仅使用字符串格式化(即,如果要格式化的变量只是 h、m 和 w 而不进行额外处理)。
但是,我想我会在他的回答中使用字符串上的布尔运算符的概念:
print("{}{}{} {}".format(h,m and " " ,m , w))
这有一个缺点,就是让阅读它的人感觉正在格式化 4 个值(技术上是这种情况,但语义上不是这样),但我确实认为这里表达的简短和简单克服了消极方面。
使用@Tsingyi 建议的参数化格式可以提高可读性,但使用以下内容:
print("{}{pad}{} {}".format(h, m , w, pad = m and " "))
注意:
在撰写本文时,以下代码无效:
希望将来我们可以做类似的事情:
print("{}{: >?} {}".format(h,m,w))
具有“可选地(如果 m 则)将其向右对齐并在其左侧增加一个空格”的语义,或者
print("{} {: <?}{}".format(h,m,w))
具有“可选地(如果 m 则)将其向左对齐并在其右侧额外填充一个空格”的语义
类似的变体可能有助于货币符号的可选格式
例如
print("{:$>?}{}".format(s))
产生一个空字符串或 $123
最后(长)注:
在我研究这个问题的某个时候,我认为我可以做这样的事情:
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()
但事实证明这会导致:
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'
也许这可以使用类似于此处描述的内容来实现:
https://stackoverflow.com/a/15975791/25412