I'm trying to make a templated string that will print values of a given dict. However, the key may or may not exist in the dict. If it doesn't exist, I'd like it to return an empty string instead.
To demonstrate what I mean, let's say I have a dict:
test_dict = { 1: "a", 2: "b"}
And a template string:
'{} {} {}'.format(test_dict.get(1), test_dict.get(2), test_dict.get(3))
I'd like the following output:
'a b '
But instead I get:
'a b None'
The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.
Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.
Use the boolean OR operator to convert None to an empty string in Python, e.g. result = None or "" . The boolean OR operator returns the value to the left if it's truthy, otherwise the value to the right is returned. Since None is a falsy value, the operation will return "" . Copied!
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
Use the dictionary's get
function. This allows you to specify a value to return if the key is not found
'{}, {}, {}'.format(test_dict.get(1,''), test_dict.get(2,''), test_dict.get(3, ''))
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