可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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)
回答1:
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)
回答2:
def xstr(s): return '' if s is None else str(s)
回答3:
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) # -> ''
回答4:
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.
回答5:
return s or ''
will work just fine for your stated problem!
回答6:
def xstr(s): return s or ""
回答7:
Functional way (one-liner)
xstr = lambda s: '' if s is None else s
回答8:
def xstr(s): return {None:''}.get(s, s)
回答9:
Variation on the above if you need to be compatible with Python 2.4
xstr = lambda s: s is not None and s or ''
回答10:
I use max function:
max(None, '') #Returns blank max("Hello",'') #Returns Hello
Works like a charm ;) Just put your string in the first parameter of the function.
回答11:
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 '')
回答12:
def xstr(s): return s if s else '' s = "%s%s" % (xstr(a), xstr(b))
回答13:
We can always avoid type casting in scenarios explained below.
customer = "John" name = str(customer) if name is