문제

I want to remove all whitespaces in my file using python. For that, I am using:

output = "file.out"

with open(output) as templist:
    templ = templist.read().splitlines()

filelist = []
for line in templ:
    if line.startswith("something"):
        filelist.append(line.strip(' '))

I managed to append the required lines, but the whitespace removing do not work. Can anybody help me? =]

도움이 되었습니까?

해결책

.strip() only removes whitespace from the start and end of a string.

I think the easiest way to go about this would be to use a regex:

import re
...
for line in templ:
    if line.startswith("something"):
        filelist.append(re.sub(r"\s+", "", line))

\s matches any kind of whitespace (spaces, newlines, tabs etc.).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top