Mark Harrison
Mark Harrison

Reputation: 304474

Most idiomatic way to convert None to empty string?

What is the most idiomatic way to do the following?

def xstr(s):
    if s is None:
        return ''
    else:
        return s

s = xstr(a) + xstr(b)

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)

Upvotes: 225

Views: 338391

Answers (17)

Jonathan
Jonathan

Reputation: 322

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

Upvotes: 1

radtek
radtek

Reputation: 36290

UPDATE:

I mainly use this method now:

some_string = 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.

OLD:

Max function worked in python 2.x but not in 3.x:

max(None, '')  # Returns blank
max("Hello", '') # Returns Hello

Upvotes: 13

maciek
maciek

Reputation: 3354

If it is about formatting strings, you can do the following:

from string import Formatter

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)

Upvotes: 2

guagay_wk
guagay_wk

Reputation: 28030

Use F string if you are using python v3.7

xstr = F"{s}"

Upvotes: -6

Willem van Ketwich
Willem van Ketwich

Reputation: 5984

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

Upvotes: 10

Pralhad Narsinh Sonar
Pralhad Narsinh Sonar

Reputation: 1454

We can always avoid type casting in scenarios explained below.

customer = "John"
name = str(customer)
if name is None
   print "Name is blank"
else: 
   print "Customer name : " + name

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.

Upvotes: 1

dorvak
dorvak

Reputation: 9709

Probably the shortest would be str(s or '')

Because None is False, and "x or y" returns y if x is false. See Boolean Operators for a detailed explanation. It's short, but not very explicit.

Upvotes: 249

SilentGhost
SilentGhost

Reputation: 319601

def xstr(s):
    return '' if s is None else str(s)

Upvotes: 177

Krystian Cybulski
Krystian Cybulski

Reputation: 11108

def xstr(s):
   return s or ""

Upvotes: 16

Peter Ericson
Peter Ericson

Reputation: 1907

Variation on the above if you need to be compatible with Python 2.4

xstr = lambda s: s is not None and s or ''

Upvotes: 4

Alex Martelli
Alex Martelli

Reputation: 881635

return s or '' will work just fine for your stated problem!

Upvotes: 72

Vinay Sajip
Vinay Sajip

Reputation: 99355

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) # -> ''

Upvotes: 109

sharjeel
sharjeel

Reputation: 6005

Use short circuit evaluation:

s = a or '' + b or ''

Since + is not a very good operation on strings, better use format strings:

s = "%s%s" % (a or '', b or '')

Upvotes: 1

Dario
Dario

Reputation: 49218

Functional way (one-liner)

xstr = lambda s: '' if s is None else s

Upvotes: 10

Kenan Banks
Kenan Banks

Reputation: 211982

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)

Upvotes: 118

tobidope
tobidope

Reputation: 560

def xstr(s):
    return {None:''}.get(s, s)

Upvotes: 6

phillc
phillc

Reputation: 7461

def xstr(s):
    return s if s else ''

s = "%s%s" % (xstr(a), xstr(b))

Upvotes: 1

Related Questions