developer tip

파이썬 문자열에서 빈 줄을 제거하는 빠른 한 줄은 무엇입니까?

optionbox 2020. 12. 15. 19:01
반응형

파이썬 문자열에서 빈 줄을 제거하는 빠른 한 줄은 무엇입니까?


불필요한 빈 줄이 포함 된 파이썬 문자열에 코드가 있습니다. 문자열에서 모든 빈 줄을 제거하고 싶습니다. 이것을하는 가장 비단뱀적인 방법은 무엇입니까?

참고 : 일반적인 코드 재 포매터를 찾는 것이 아니라 한 줄 또는 두 줄로 된 간단한 코드입니다.

감사!


어때 :

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

text가능한 외부 줄이있는 문자열은 어디에 있습니까?


"\n".join([s for s in code.split("\n") if s])

편집 2 :

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

제 최종 버전이라고 생각합니다. 코드 믹싱 라인 엔딩에서도 잘 작동합니다. 공백이있는 줄은 비어 있다고 생각하지 않지만, 그렇다면 간단한 s.strip () 대신 사용할 수 있습니다.


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()]

가독성에 유용 할 수 있습니다.


공백이있는 NEWLINES 및 빈 줄 제거에 대한 강의

"t"는 텍스트가있는 변수입니다. 당신은 "s"변수를 보게 될 것입니다. 그것은 괄호의 주요 세트를 평가하는 동안에 만 존재하는 임시 변수입니다. (이 lil python 것들의 이름을 잊어 버렸습니다.)

먼저 "t"변수를 설정하여 새 줄을 만듭니다.

>>> t='hi there here is\na big line\n\nof empty\nline\neven some with spaces\n       \nlike that\n\n    \nokay now what?\n'

삼중 따옴표를 사용하여 변수를 설정하는 또 다른 방법이 있습니다.

somevar="""
   asdfas
asdf

  asdf

  asdf

asdf
""""

다음은 "인쇄"없이 볼 때의 모습입니다.

>>> t
'hi there here is\na big line\n\nof empty\nline\neven some with spaces\n       \nlike that\n\n    \nokay now what?\n' 

실제 줄 바꿈으로 보려면 인쇄하십시오.

>>> print t
hi there here is
a big line

of empty
line
even some with spaces

like that


okay now what?

모든 빈 줄 제거 명령 (공백 포함) :

그래서 somelines 개행은 개행 일 뿐이고 일부는 공백이있어서 개행처럼 보입니다.

공백으로 보이는 모든 줄을 제거하려면 (개행 문자 만 있거나 공백도있는 경우)

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?

또는:

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?

NOTE: that strip in t.strip().splitline(True) can be removes so its just t.splitlines(True), but then your output can end with an extra newline (so that removes the final newline). The strip() in the last part s.strip("\r\n").strip() and s.strip() is what actually removes the spaces in newlines and newlines.

COMMAND REMOVE ALL BLANK LINES (BUT NOT ONES WITH SPACES):

Technically lines with spaces should NOT be considered empty, but it all depends on the use case and what your trying to achieve.

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
hi there here is
a big line
of empty
line
even some with spaces

like that

okay now what?

** NOTE ABOUT THAT MIDDLE strip **

That middle strip there, thats attached to the "t" variable, just removes the last newline (just as the previous note has stated). Here is how it would look like without that strip being there (notice that last newline)

With 1st example (removing newlines and newlines with spaces)

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
.without strip new line here (stackoverflow cant have me format it in).

With 2nd example (removing newlines only)

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
hi there here is
a big line
of empty
line
even some with spaces

like that

okay now what?
.without strip new line here (stackoverflow cant have me format it in).

The END!


By using re.sub function

re.sub(r'^$\n', '', s, flags=re.MULTILINE)

This one will remove lines of spaces too.

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


Here is a one line solution:

print("".join([s for s in mystr.splitlines(True) if s.strip()]))

And now for something completely different:

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'

Episode 2:

This one doesn't work on 1.5 :-(

BUT not only does it handle universal newlines and blank lines, it also removes trailing whitespace (good idea when tidying up code lines IMHO) AND does a repair job if the last meaningful line is not terminated.

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)

expanding on ymv's answer, you can use filter with join to get desired string,

"".join(filter(str.strip, sample_string.splitlines(True)))

This code removes empty lines (with or without whitespaces).

import re    
re.sub(r'\n\s*\n', '\n', text, flags=re.MULTILINE)

I wanted to remove a bunch of empty lines and what worked for me was:

if len(line) > 2:
    myfile.write(output)

I went with 2 since that covered the \r\n. I did want a few empty rows just to make my formatting look better so in those cases I had to use:

print("    \n"

ReferenceURL : https://stackoverflow.com/questions/1140958/whats-a-quick-one-liner-to-remove-empty-lines-from-a-python-string

반응형