Python: najbardziej idiomatyczny sposób konwersji None na empty string?

Jaki jest najbardziej idiomatyczny sposób, aby wykonać następujące czynności?

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

s = xstr(a) + xstr(b)

Update: włączam sugestię Trypticha, aby użyć str(s), co sprawia, że ta rutyna działa dla innych typów oprócz ciągów. Jestem pod ogromnym wrażeniem sugestii Lambdy Vinaya Sajipa, ale chcę, aby mój kod był stosunkowo prosty.

def xstr(s):
    if s is None:
        return ''
    else:
        return str(s)
Author: Mark Harrison, 2009-06-23

15 answers

Jeśli chcesz, aby Twoja funkcja zachowywała się jak wbudowana str(), ale zwracała pusty łańcuch, gdy argument jest None, zrób to:

def xstr(s):
    if s is None:
        return ''
    return str(s)
 66
Author: Triptych,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-23 19:28:18
def xstr(s):
    return '' if s is None else str(s)
 119
Author: SilentGhost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-13 13:55:33

Jeśli wiesz, że wartość zawsze będzie ciągiem znaków lub 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) # -> ''
 84
Author: Vinay Sajip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-23 22:01:12

Prawdopodobnie Najkrótsza byłaby str(s or '')

Ponieważ None jest False, A" x lub y " zwraca y, Jeśli X jest false. Zobacz operatory logiczne , aby uzyskać szczegółowe wyjaśnienie. Jest krótki, ale niezbyt wyraźny.

 57
Author: dorvak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-31 12:36:51

return s or '' będzie działać dobrze dla stwierdzonego problemu!

 49
Author: Alex Martelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-24 03:08:53
def xstr(s):
   return s or ""
 13
Author: Krystian Cybulski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-24 03:56:07

Functional way (one-liner)

xstr = lambda s: '' if s is None else s
 7
Author: Dario,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-23 19:31:58
def xstr(s):
    return {None:''}.get(s, s)
 6
Author: tobidope,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-23 19:28:12

Wariacja na temat powyższego, jeśli chcesz być kompatybilny z Pythonem 2.4

xstr = lambda s: s is not None and s or ''
 4
Author: Peter Ericson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-24 03:37:06

Używam funkcji max:

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

Działa jak urok ;) wystarczy umieścić swój ciąg w pierwszym parametrze funkcji.

 3
Author: radtek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-23 19:56:45

Zgrabny jeden liner do zrobienia tego budynku na niektórych z innych odpowiedzi:

s = (lambda v: v or '')(a) + (lambda v: v or '')(b)

Lub nawet po prostu:

s = (a or '') + (b or '')
 3
Author: Willem van Ketwich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-13 00:39:17
def xstr(s):
    return s if s else ''

s = "%s%s" % (xstr(a), xstr(b))
 1
Author: phillc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-23 19:25:57

W scenariuszach opisanych poniżej zawsze możemy uniknąć typowania.

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

W powyższym przykładzie w przypadku, gdy zmienna customer ' s value jest None, zostanie ona następnie rzucona podczas przypisywania do 'name'. Porównanie w klauzuli "jeśli" zawsze się nie powiedzie.

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)

Powyższy przykład będzie działał poprawnie. Takie scenariusze są bardzo powszechne, gdy wartości są pobierane z adresu URL, JSON lub XML, a nawet wartości wymagają dalszego odlewania typu dla jakiejkolwiek manipulacji.

 1
Author: Pralhad Narsinh Sonar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-26 10:27:53

Jeśli chodzi tylko o formatowanie łańcuchów, możesz wykonać następujące czynności:

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)
 0
Author: maciek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-16 10:39:16

Użyj oceny zwarcia:

s = a or '' + b or ''

Ponieważ + nie jest zbyt dobrą operacją na łańcuchach, lepiej używać łańcuchów formatujących:

s = "%s%s" % (a or '', b or '')
 -1
Author: sharjeel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-23 19:37:21