Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print empty string if variable is None [duplicate]

Tags:

python

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'
like image 537
doctopus Avatar asked Jul 26 '19 21:07

doctopus


People also ask

Is empty string same as 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.

How do you print an empty string in Python?

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.

How do you replace None with empty string in Python?

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!

How do you indicate that string might be NULL?

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.


1 Answers

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, ''))
like image 119
MichaelD Avatar answered Sep 21 '22 10:09

MichaelD