218

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)
3
  • 1
    "If s is None, then return an empty string; otherwise, return [string of] s." The code from the question reads like a normal English sentence too.
    – Roger Pate
    Jan 2, 2010 at 19:37
  • 3
    a) If the string s came from a dict lookup where the key was not found, then use dict.get(key, '')
    – smci
    Jul 27, 2019 at 1:38
  • b) If you only want this string-conversion for output formatting (e.g. for print), then you can directly do '... {}'.format(dict.get(1))`
    – smci
    Jul 27, 2019 at 1:41

17 Answers 17

240

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.

6
  • 25
    This doesn't work if s is 0, False, or any falsy value
    – wisbucky
    Aug 17, 2015 at 18:15
  • 9
    Well, that's not mentioned in the op's requirement, so I don't see your point here.
    – dorvak
    Sep 10, 2015 at 11:20
  • 4
    @dorvak The OP is quite explicit about the requirement that the output should be '' iff s is None. All other input should return s (or str(s) in the revised request).
    – StvnW
    Oct 29, 2015 at 22:49
  • str(...) around s only, converting an empty string to string is a nonsense... also, to the revised request: def xstr(s): return str(s) or ""
    – fortea
    Dec 24, 2017 at 12:07
  • 3
    @fortea: that won't work. If s is None, the result of xstr() should be an empty string, but str(None) gives the string "None", which is what is returned (since the string "None" is not a falsy value.
    – dreamlax
    Jul 12, 2018 at 1:13
175
def xstr(s):
    return '' if s is None else str(s)
8
  • 4
    This syntax was introduced in 2.5; for earlier versions of Python, you can use return s is not None and s or ''.
    – Ben Blank
    Jun 24, 2009 at 0:16
  • 8
    I'd turn it around to emphasize the more commen case: return s if s is not None else ""
    – Ber
    Jun 24, 2009 at 7:45
  • 5
    @Ber: I would keep it as is, to avoid a double negative.
    – Nikhil
    Jun 26, 2009 at 7:09
  • 8
    This is a good example of how .. and .. or .. fails and why if-else is preferred. There're two subtle bugs in s is not None and s or ''.
    – Roger Pate
    Jan 2, 2010 at 19:31
  • 1
    return '' if not s else str(s)
    – Iqbal
    Mar 17, 2016 at 13:44
117

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)
6
  • 1
    I'm keeping the else, but thanks for the str(s) tip so multiple types can be handled. nice! Jul 1, 2009 at 9:39
  • 20
    Or simply xstr = lambda s: '' if s is None else str(s) May 21, 2013 at 22:39
  • 3
    I love typing if not s: instead of if s is None
    – guneysus
    Dec 6, 2015 at 15:09
  • 9
    @guneysus They aren’t the same: not False == True but False is None == False.
    – Lynn
    Feb 25, 2016 at 13:39
  • Thanks @Lynn you are right. I realized my fault. But I know (or assume) s always a in str/unicode type or None. Yes, False is a value but I prefer this way that saves my keyboard and eyes ;)
    – guneysus
    Feb 25, 2016 at 23:03
107

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) # -> ''
7
  • 1
    by far the most pythonic. Uses the fact that python treats None, an empty list, an empty string, 0, etc as false. Also uses the fact that the or statement returns the first element that is true or the last element given to the or (or groups of ors). Also this uses lambda functions. I would give you +10 but obviously it wont let me.
    – Matt
    Jun 23, 2009 at 22:59
  • 12
    This will convert 0 and False (and anything else that evaluates to False when passed to bool())
    – Arkady
    Jun 24, 2009 at 0:12
  • 9
    I don't think it's "by far the most pythonic". It's a common idiom in other languages, and I don't think it's wrong to use it in Python, but conditional expressions where introduced precisely to avoid tricks like this. Jun 24, 2009 at 4:44
  • 2
    This makes [], {}, etc. give the same result as None, which isn't desired. xstr(False), in particular, should be "False" instead of "". Abusing lambdas makes for a poor example, use def xstr(s): return s or "" ir you want to keep it all on one line.
    – Roger Pate
    Feb 9, 2010 at 20:22
  • 5
    Note that I qualified my answer at the outset with "If you know that the value will always either be a string or None". Feb 9, 2010 at 22:46
69

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

6
  • 4
    Worth noting that this will give a different result for when s is False or 0 (which isn't the original string question, but the updated one.) Apr 30, 2010 at 1:42
  • 3
    @Oddthinking s = False or s = 0 would most likely be an edge case in it's use and could be easily mitigated by writing it as return str(s or '') May 13, 2017 at 0:45
  • @WillemvanKetwich: That has exactly the same problem: s(False) should return 'False', not ''. s(0) should return '0', not ''. Likewise for an object that defines __bool__ or __nonzero__. May 13, 2017 at 3:27
  • @Oddthinking I see your point. In any case, if it is used exclusively for string objects such as in the OP's question it shouldn't be an issue. May 13, 2017 at 3:55
  • @WillemvanKetwich: Have a look at the updated question and the caveat in my comment - this has been covered, May 13, 2017 at 6:38
15
def xstr(s):
   return s or ""
2
  • 5
    This returns '' for 0, [], {}, False and false-like values, which is not what the poster asked for.
    – StvnW
    Oct 29, 2015 at 23:01
  • 1
    just put str([...]) around s: def xstr(s): return str(s) or ""
    – fortea
    Dec 24, 2017 at 12:01
12

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
2
  • 5
    This works because 'str' > 'NoneType', and is CPython specific. From the manual: "Objects of different types except numbers are ordered by their type names". Also, this won't work in Python 3000, since inter-type comparison is no longer allowed (TypeError: unorderable types: str() > NoneType()). See How does Python compare string and int?
    – plok
    Jun 30, 2014 at 7:50
  • Good to know thanks, so not a good idea moving forward with python 3.x compatible code.
    – radtek
    Jul 4, 2014 at 13:25
10

Functional way (one-liner)

xstr = lambda s: '' if s is None else s
4
  • 1
    "def xstr(s): return '' if s is None else s " is an on-liner too, python is not as strict with whitespaces after all Jun 23, 2009 at 19:35
  • 2
    It's no real one-liner, it's just written in one line g
    – Dario
    Jun 23, 2009 at 19:42
  • 1
    in what sense it's not a real onliner? check in your interpreter - it's not a syntax error. for all intents and purposes it's way real than lambda ^_^ Jun 23, 2009 at 19:47
  • 4
    PEP 8 species that you should use def instead of assigning lambda to a variable. The only real advantage of lambda is that you can write as a part of expression(passing to another function for instance) and that advantage is lost in code like this. I used to do this too, until I noticed that def can be written in one line, and then PEP 8 showed me the way to go. ALWAYS follow the python gods.
    – Guy
    Feb 26, 2014 at 14:39
10

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 '')
4
  • Why even mention (lambda v: v or '')?
    – Tvde1
    Feb 6, 2019 at 18:40
  • Why not? 2 tips for the price of 1! 😀 Feb 6, 2019 at 22:32
  • 1
    Please be aware that False and empty list will also be turned to ''.
    – Nik O'Lai
    Sep 20, 2019 at 17:45
  • same for 0, etc. Apr 26, 2020 at 10:47
6
def xstr(s):
    return {None:''}.get(s, s)
6
  • I think, it is rather pythonic -- how about this one: "xstr = lambda s : {None:''}.get(s,s)" -- reduces the whole thing to a one-liner.
    – Juergen
    Jun 23, 2009 at 19:36
  • 16
    Unnecessarily slow (extra dict construction and lookup), and harder to read. Pretty unpythonic. Jun 23, 2009 at 19:37
  • You're right. It's rather perlish but it avoids a conditional jump in python bytecode.
    – tobidope
    Jun 23, 2009 at 19:40
  • 4
    The get() function call implies at least one additional conditional jump. Jun 23, 2009 at 19:45
  • 1
    I wouln't be able to say what this should do without knowing the question or looking up get.
    – Dario
    Jun 23, 2009 at 19:46
4

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

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

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)
1
def xstr(s):
    return s if s else ''

s = "%s%s" % (xstr(a), xstr(b))
1
  • 5
    This will return an empty string for all false-like values, which is not what the poster asked for. Jun 23, 2009 at 19:29
1

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.

0

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 '')
3
  • 2
    This also will convert 'a' to empty strings for all false-like values, not just None. For instance, empty tuples, lists, and dicts will convert to empty strings, which is not what the OP specified. Jun 23, 2009 at 19:41
  • + is a perfectly good operator for two strings. It's when you try to use it to join dozens that you have trouble. For two, it'll probably be faster than other options; either way, it's in the noise.
    – kquinn
    Jun 23, 2009 at 22:10
  • +1 for me cause this is exactly what I need in my case: lambda or function to replace a single operator (or) seems a bit of an overkill for me... I dont have cases of other falsly values - either str or None. Other than the comment on the + operator, which might depend on specific scenario and might need benchmarking, this answer does not deserve a -1
    – urban
    Nov 28, 2018 at 10:22
0

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
-6

Use F string if you are using python v3.7

xstr = F"{s}"
1
  • 3
    This is wrong and returns the string 'None' if s is None.
    – Lawrence
    Oct 17, 2019 at 6:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.