试图理解 .strip

Trying to understand .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('\t') 替换 .strip('') 但我得到相同的输出:

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') 没有剥离标签?

您忘记为您的 else 条件中的适用行实际应用 strip。此外,使用 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

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

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