سؤال

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