首页 > 解决方案 > 试图理解 .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')不剥离标签?

标签: pythonpython-3.xfilestrip

解决方案


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

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

推荐阅读