Suppose I have 3 python strings and I can format all 3 of them with 2 separating spaces between them like in the following:
h="hello"
m="my"
w="world"
print("{} {} {}".format(h,m,w))
or using
print("%s %s %s" % (h,m,w))
Suppose now that I am sure that both h and w have values but m might be an empty string. The two code fragments above would result with "hello{two speces here}world
.
I know that I can use different functions and conditional expressions to either do the formatting by code such as in
print(h+" " + m+(" " if len(m)>0 else "") + w)
or pick a different formatting string
print(("{} {} {}" if len(m)>0 else "{}{} {}").format(h,m,w))
based on the length of m.
My Q is Can this be done using the formatting strings ? (e.g. some format modifier that will pad with 1 space if its parameter is not empty).
not sure it's very convenient, but there's a way, generating space or not depending on the "truth" value of the strings:
h="hello"
m="my"
w="world"
print("{}{}{}{}".format(h," "*bool(m),m,w))
result:
hello my world
now set m
to empty string, you get
hello world
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With