python - 试图理解 .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')
不剥离标签?
解决方案
Strip 方法只能从字符串的开头或结尾删除字符。尝试使用替换。
>>> line = "Animals: cat, dog, frog, cheetah, tiger"
>>> line.replace('\t', ' ')
'Animals: cat, dog, frog, cheetah, tiger'
推荐阅读
- c++ - 错误:在将值分配给指针时,不应忽略 void 值
- git - 尝试克隆私有 git 存储库,不要求提供 uid/pwd,获取“核心”文件
- winapi - VariantClear 发布 VT_DISPATCH -vs- MSDN 文档
- typescript - 如何在打字稿中定义 Option Partial?
- php - 通过自定义字段获取帖子顺序
- java - 在多线程中使用 Yield
- javascript - 向左/向右切换 div 无法正常工作
- listview - Xamarin ListView:展开项目
- css - 如何在不将它们包装在容器中的情况下连续对齐 div?
- node.js - 无法在 Angular 7 中创建项目?