Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
update:
I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.
def xstr(s):
if s is None:
return ''
else:
return str(s)
–
–
–
–
–
–
–
If you actually want your function to behave like the str()
built-in, but return an empty string when the argument is None, do this:
def xstr(s):
if s is None:
return ''
return str(s)
–
–
If you know that the value will always either be a string or None:
xstr = lambda s: s or ""
print xstr("a") + xstr("b") # -> 'ab'
print xstr("a") + xstr(None) # -> 'a'
print xstr(None) + xstr("b") # -> 'b'
print xstr(None) + xstr(None) # -> ''
–
–
–
–
–
–
–
–
–
–
–
some_string or ''
If some_string was not NoneType
, the or
would short circuit there and return it, otherwise it returns the empty string.
Max function worked in python 2.x but not in 3.x:
max(None, '') # Returns blank
max("Hello", '') # Returns Hello
–
–
–
–
A neat one-liner to do this building on some of the other answers:
s = (lambda v: v or '')(a) + (lambda v: v or '')(b)
or even just:
s = (a or '') + (b or '')
–
–
–
class NoneAsEmptyFormatter(Formatter):
def get_value(self, key, args, kwargs):
v = super().get_value(key, args, kwargs)
return '' if v is None else v
fmt = NoneAsEmptyFormatter()
s = fmt.format('{}{}', a, b)
–
In the example above in case variable customer's value is None the it further gets casting while getting assigned to 'name'. The comparison in 'if' clause will always fail.
customer = "John" # even though its None still it will work properly.
name = customer
if name is None
print "Name is blank"
else:
print "Customer name : " + str(name)
Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.
–
–
–
Same as Vinay Sajip's answer with type annotations, which precludes the needs to str()
the result.
def xstr(s: Optional[str]) -> str:
return '' if s is None else s
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.