首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试理解.strip

尝试理解.strip
EN

Stack Overflow用户
提问于 2018-05-28 08:29:51
回答 2查看 122关注 0票数 1

我有一个名为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')没有剥离标签?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-28 08:35:51

您忘记了为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
票数 0
EN

Stack Overflow用户

发布于 2018-05-28 09:48:57

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

>>> line = "Animals:    cat, dog, frog, cheetah, tiger"
>>> line.replace('\t', ' ')
'Animals: cat, dog, frog, cheetah, tiger'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50557727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档