首页 > 解决方案 > 如何从python中的文件中删除符号?

问题描述

我很难"//!"从我试图用 python 解析的文件的句子开头删除它。

with open("dwe.txt", "r") as file1:
    for row in file1:
        print(row.rstrip('//!'))

预期产出

The flag should not process everything that was given at the time 
it was processing.

实际输出

//! The flag should not process everything that was given at the time 
//! it was processing.  

标签: pythonfile

解决方案


正如@Kevin 提到的,rstrip(),lstrip()strip()删除包含字符串的所有变体,直到它遇到一个不匹配的字符,所以它不适合您的操作。例如:

>>> 'barmitzvah'.lstrip('bar')
'mitzvah'
>>> 'rabbit'.lstrip('bar')
'it'
>>>'rabbarabbadoo'.lstrip('bar')
'doo'

尝试startswith()改用:

with open("dwe.txt", "r") as file1: 
    for row in file1.readlines(): 
        if row.startswith('//! '):
            print(row[3:])

推荐阅读