Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional space in python string formatting

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).

like image 371
epeleg Avatar asked Feb 04 '23 04:02

epeleg


1 Answers

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
like image 155
Jean-François Fabre Avatar answered Feb 06 '23 18:02

Jean-François Fabre