试图理解.strip

时间:2018-05-28 00:29:51

标签: python python-3.x file strip

我有一个名为input.py的文件,其中包含以下内容:

#This is a file of categories
Animals:    cat, dog, frog, cheetah, tiger
Items:      desk, chair, bus, cups, pencil

Technology: cellphone, TV, laptop, wifi-router
    #That's the end of the file

我希望过滤掉所有以#开头的空行和行,以生成output.py

Animals:    cat, dog, frog, cheetah, tiger
Items:      desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router

我的代码是

with open('input.py', 'r') as infile, open('output.py', 'w') as outfile:
    for line in infile:
        if line[0].strip('') == '#' or line == '\n':
            pass
        else:
            outfile.write(line)

但它不会从标签开始剥离线条。我尝试用.strip('')替换.strip('\t'),但我得到了相同的输出:

Animals:    cat, dog, frog, cheetah, tiger
Items:      desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router
    #That's the end of the file

为什么.strip('').strip('\t')没有剥离标签?

2 个答案:

答案 0 :(得分:1)

Strip方法只能从字符串的开头或结尾删除字符。请尝试使用替换。

>>> line = "Animals:    cat, dog, frog, cheetah, tiger"
>>> line.replace('\t', ' ')
'Animals: cat, dog, frog, cheetah, tiger'

答案 1 :(得分:0)

您忘记在strip条件下实际应用else适用的行。此外,使用str.startswith来测试您的行是否以特定字符串开头。

这是一个完整的例子:

from io import StringIO

mystr = StringIO("""Animals:    cat, dog, frog, cheetah, tiger
Items:      desk, chair, bus, cups, pencil

Technology: cellphone, TV, laptop, wifi-router
    #That's the end of the file""")

with mystr as infile:
    for line in infile:
        if line.strip().startswith('#') or line == '\n':
            pass
        else:
            print(line.strip())

结果:

Animals:    cat, dog, frog, cheetah, tiger
Items:      desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router