Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with null values using Python format

I'm looking for a way to essentially strip out the extra period if a value is null or None. If myvar doesn't exist, it should print abc.xyz

myvar="def"
print "abc.{0}.xyz".format(myvar)
abc.def.xyz

myvar=""
print "abc.{0}.xyz".format(myvar)
abc..xyz
like image 900
sdot257 Avatar asked Jun 21 '26 08:06

sdot257


1 Answers

If a character is present in the original string it will be included regardless after calling format for it. What needs to be done is to modify the input such that it will include whatever extra character when the intended value is present. Consider the following (encapsulated in a function as a demo):

def demo(value):
    print("abc.{0}xyz".format(value + '.' if value else ''))

Example usage:

>>> demo('def')
abc.def.xyz
>>> demo('')
abc.xyz
like image 120
metatoaster Avatar answered Jun 24 '26 01:06

metatoaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!