如何从python中的文件中删除符号?

时间:2019-01-07 14:08:41

标签: python file

我很难从要在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.  

2 个答案:

答案 0 :(得分:2)

如@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:])

答案 1 :(得分:0)

在@Adam评论中,您只需将rstrip更改为lstrip

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.