Ahmed Ahmed
Ahmed Ahmed

Reputation: 1

How can i remove symbols from file in python?

I'm having a hard time removing this "//!" from the beginning of my sentences on the file that I'm trying to parse in python.

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

Expected output

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

Actual output

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

Upvotes: 0

Views: 372

Answers (2)

r.ook
r.ook

Reputation: 13868

As @Kevin mentioned, rstrip(), lstrip() and strip() removes all variations of the included string until it hits a character that isn't matched, so it's not ideal for your operation. E.g.:

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

Try using startswith() instead:

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

Upvotes: 2

Josh Friedlander
Josh Friedlander

Reputation: 11657

As @Adam comments, you just need to change rstrip to 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.

Upvotes: 0

Related Questions