Łączenie wielu łańcuchów, jeśli nie są puste w Pythonie
Mam cztery struny i każdy z nich może być pusty. Muszę je połączyć w jeden ciąg ze spacjami między nimi. Jeśli używam:
new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4
Wynikiem jest Spacja na początku nowego ciągu, jeśli {[1] } jest pusty. Ponadto mam trzy puste spacje, jeśli string2
i {[3] } są puste.
Jak mogę je łatwo połączyć bez spacji, jeśli ich nie potrzebuję?
84
3 answers
>>> strings = ['foo','','bar','moo']
>>> ' '.join(filter(None, strings))
'foo bar moo'
Używając None
W filter()
call, usuwa wszystkie falsyfikaty.
205
Author: ThiefMaster,
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
2011-12-24 20:25:31
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
2011-12-24 20:25:31
Jeśli wiesz, że ciągi nie mają wiodącej / końcowej spacji:
>>> strings = ['foo','','bar','moo']
>>> ' '.join(x for x in strings if x)
'foo bar moo'
Inaczej:
>>> strings = ['foo ','',' bar', ' ', 'moo']
>>> ' '.join(x.strip() for x in strings if x.strip())
'foo bar moo'
I jeśli któryś z łańcuchów ma nie-wiodące / końcowe białe spacje, może być konieczne jeszcze ciężej pracować. Proszę wyjaśnić, co tak naprawdę masz.
23
Author: John Machin,
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
2011-12-24 20:51:30
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
2011-12-24 20:51:30
strings = ['foo','','bar','moo']
' '.join([x for x in strings if x is not ''])
'foo bar moo'
-2
Author: Greg Brown,
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
2011-12-24 20:31:22
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
2011-12-24 20:31:22