相关文章推荐
不开心的盒饭  ·  MyBatis中mapper.xml中for ...·  10 月前    · 
焦虑的脸盆  ·  javascript 添加行 ...·  1 年前    · 
淡定的葡萄  ·  Excel VBA入门(8): ...·  1 年前    · 
宽容的苦咖啡  ·  txt ...·  1 年前    · 
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 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
                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
                @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
                @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
                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
                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

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)
                I'm keeping the else, but thanks for the str(s) tip so multiple types can be handled.  nice!
– Mark Harrison
                Jul 1, 2009 at 9: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

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) # -> ''
                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
                This will convert 0 and False (and anything else that evaluates to False when passed to bool())
– Arkady
                Jun 24, 2009 at 0:12
                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.
– Roberto Bonvallet
                Jun 24, 2009 at 4:44
                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
                Note that I qualified my answer at the outset with "If you know that the value will always either be a string or None".
– Vinay Sajip
                Feb 9, 2010 at 22:46
                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.)
– Oddthinking
                Apr 30, 2010 at 1:42
                @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 '')
– Willem van Ketwich
                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__.
– Oddthinking
                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.
– Willem van Ketwich
                May 13, 2017 at 3:55
                @WillemvanKetwich: Have a look at the updated question and the caveat in my comment - this has been covered,
– Oddthinking
                May 13, 2017 at 6:38
                This returns '' for 0, [], {}, False and false-like values, which is not what the poster asked for.
– StvnW
                Oct 29, 2015 at 23:01
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
                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
                "def xstr(s):     return '' if s is None else s " is an on-liner too, python is not as strict with whitespaces after all
– SilentGhost
                Jun 23, 2009 at 19:35
                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 ^_^
– SilentGhost
                Jun 23, 2009 at 19:47
                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

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 '')
                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
                Unnecessarily slow (extra dict construction and lookup), and harder to read. Pretty unpythonic.
– Kenan Banks
                Jun 23, 2009 at 19:37
                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
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)
                This will return an empty string for all false-like values, which is not what the poster asked for.
– Kenan Banks
                Jun 23, 2009 at 19:29

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.

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. – Kenan Banks 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

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.