问题描述:

im trying to figure out why it wont let me remove the newline characters, my code:

 def parsefile(f):

for line in open(f):

li=line.strip()

if not li.startswith("%"):

if not li.startswith(' '):

if not li.startswith('\n'):

print(line.replace("\n",""))

#print(line.rstrip())

even though i have told it to ignore the '\n' is still leaving spaces in the output, which looks like this

 type1

type2

type3

type4

when it should just be

 type1

type2

type3

type4

. my guess is its something to do with my loop leaving the spaces.

the file im accessing is:

 %spam

type1

type2

type3

%spam

type4

网友答案:

As far as I understood, you actually want to skip empty lines, newline chars are already gone after strip.

def parsefile(f):
    for line in open(f):
        li=line.strip()
        if li and not li.startswith("%"):
            print(li)

When you read a file line by line, you're getting every line including empty with the newline chars, so for empty lines you're getting just "\n" which becomes "" after stripping. As explained in the comments, if li: in this case is a short for of if li != "":.

网友答案:

This option can help you:

def parse_file(filename):
    f = open(filename)
    for line in f.readlines():
        li=line.lstrip()
        if li and (li[0] != "%"):
            print(li)

Note: You can delete left whitespaces using lstrip.

相关阅读:
Top