Python: most idiomatic way to convert None to empty string?

前端 未结 16 1141
[愿得一人]
[愿得一人] 2020-11-28 02:21

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)


        
相关标签:
16条回答
  • 2020-11-28 02:39
    def xstr(s):
        return {None:''}.get(s, s)
    
    0 讨论(0)
  • 2020-11-28 02:41

    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 讨论(0)
  • 2020-11-28 02:42

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

    0 讨论(0)
  • 2020-11-28 02:45
    def xstr(s):
        return '' if s is None else str(s)
    
    0 讨论(0)
  • 2020-11-28 02:45

    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.

    0 讨论(0)
  • 2020-11-28 02:46

    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 '')
    
    0 讨论(0)
提交回复
热议问题