epe*_*leg 9 python string-formatting
假设我有3个python字符串,我可以格式化所有3个字符串,它们之间有2个分隔空格,如下所示:
h="hello"
m="my"
w="world"
print("{} {} {}".format(h,m,w))
Run Code Online (Sandbox Code Playgroud)
或使用
print("%s %s %s" % (h,m,w))
Run Code Online (Sandbox Code Playgroud)
现在假设我确定h和w都有值,但m可能是一个空字符串.上面的两个代码片段将导致"hello{two speces here}world.
我知道我可以使用不同的函数和条件表达式来通过代码进行格式化
print(h+" " + m+(" " if len(m)>0 else "") + w)
Run Code Online (Sandbox Code Playgroud)
或选择不同的格式字符串
print(("{} {} {}" if len(m)>0 else "{}{} {}").format(h,m,w))
Run Code Online (Sandbox Code Playgroud)
基于m的长度.
我的问题是可以使用格式化字符串来完成吗?(例如,如果参数不为空,将填充1个空格的某些格式修饰符).
不确定它是否非常方便,但有一种方法,根据字符串的"真值"值产生或不产生空间:
h="hello"
m="my"
w="world"
print("{}{}{}{}".format(h," "*bool(m),m,w))
Run Code Online (Sandbox Code Playgroud)
结果:
hello my world
Run Code Online (Sandbox Code Playgroud)
现在设置m为空字符串,你得到
hello world
Run Code Online (Sandbox Code Playgroud)