Witchslayer
Witchslayer

Reputation: 3

Removing Specific Characters from txt in Python 3.5

I was trying to create a program that would remove * or ! from lines if they started with said characters. Therefore, something like:

*81
!81

Would change to be:

81
81

This is the code I'm using as of now:

input("Hello")
with open("Test.txt",'r') as c:
    lines = c.readlines()
    c.close()
with open("Test.txt",'w') as c:
    c.truncate()
    for line in lines:
        if line.startswith("!") or line.startswith("*") == False:
            c.write(line)
        if line.startswith("!") or line.startswith("*") == True:
            new_line = line.translate({ord(c): None for c in '* !'})
            print(new_line)
            c.write(new_line)

    c.close()

However, only the stars will be removed, what is wrong with this?

Upvotes: 0

Views: 45

Answers (2)

DigiGen
DigiGen

Reputation: 11

A solution that uses a regular expression substitution:

import re

with open("Test.txt",'r+') as c:
        inp = c.read()
        out = re.sub(r'^([\*!])(.*)', r'\2', inp, flags=re.MULTILINE)
        c.seek(0)
        c.write(out)
        c.truncate()

Note, the regular expression above will replace only the leading '*' or '!'. Thus, lines that start with any combination of the characters like

*!80
!*80
**80

would be replaced by

!80
*80
*80

To replace all leading '*' and '!' on lines that start with the characters, change pattern to

'^([\*!]+)(.*)'

Upvotes: 0

tdelaney
tdelaney

Reputation: 77357

Your boolean conditions aren't correct, you need the test on all conditions and use and in that first if

if line.startswith("!") == False and line.startswith("*") == False:
    ...

or better yet, use not

if not (line.startswith("!") or line.startswith("*")):
    ...

And even better still, extract the token you are interested in and check it against an exclusion list

with open("Test.txt",'r') as c:
    lines = c.readlines()

with open("Test.txt",'w') as c:
    for line in lines:
        if line[0] in "*!":
            line = line[1:]
        c.write(line)

Upvotes: 0

Related Questions