我有一个名为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')
没有剥离标签?
发布于 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
发布于 2018-05-28 09:48:57
方法只能从字符串的开头或结尾删除字符。请尝试使用replace。
>>> line = "Animals: cat, dog, frog, cheetah, tiger"
>>> line.replace('\t', ' ')
'Animals: cat, dog, frog, cheetah, tiger'
https://stackoverflow.com/questions/50557727
复制相似问题