Что быстрая острота должна удалить пустые строки из строки Python?

найдите и xargs являются Вашими друзьями. Используйте их для фильтрации списка файлов, а не grep's - исключают

Попытка что-то как

find . -not -name '*.png' -o -type f -print | xargs grep -icl "foo="
57
задан Andrew Wagner 17 July 2009 в 00:21
поделиться

5 ответов

How about:

text = os.linesep.join([s for s in text.splitlines() if s])

where text is the string with the possible extraneous lines?

83
ответ дан 24 November 2019 в 19:27
поделиться

This one will remove lines of spaces too.

re.replace(u'(?imu)^\s*\n', u'', code)

2
ответ дан 24 November 2019 в 19:27
поделиться
"\n".join([s for s in code.split("\n") if s])

Edit2:

text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")])

I think that's my final version. It should work well even with code mixing line endings. I don't think that line with spaces should be considered empty, but if so then simple s.strip() will do instead.

15
ответ дан 24 November 2019 в 19:27
поделиться

А теперь кое-что совершенно другое:

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import string, re
>>> tidy = lambda s: string.join(filter(string.strip, re.split(r'[\r\n]+', s)), '\n')
>>> tidy('\r\n   \n\ra\n\n   b   \r\rc\n\n')
'a\012   b   \012c'

Эпизод 2:

Этот не работает в 1.5: - (

НО он не только обрабатывает универсальные символы новой строки и пустые символы. строк, он также удаляет конечные пробелы (хорошая идея при наведении порядка в строках кода, ИМХО) И выполняет ремонтную работу, если последняя значимая строка не прерывается.

import re
tidy = lambda c: re.sub(
    r'(^\s*[\r\n]+|^\s*\Z)|(\s*\Z|\s*[\r\n]+)',
    lambda m: '\n' if m.lastindex == 2 else '',
    c)
0
ответ дан 24 November 2019 в 19:27
поделиться
filter(None, code.splitlines())
filter(str.strip, code.splitlines())

эквивалентны

[s for s in code.splitlines() if s]
[s for s in code.splitlines() if s.strip()]

и могут быть полезны для удобства чтения

12
ответ дан 24 November 2019 в 19:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: