jurson201
jurson201

Reputation: 19

Python - replace few characters

i trying to understand that.

I must delete few characters in my string loaded from .txt

f = open("my_file.txt")

myList = [".", ",", "-"]
removed = ""

for i in myList:
    removed += f.read().replace(f'{i}', '')

print(removed)

My solution working only on one char, why?

Upvotes: 1

Views: 49

Answers (3)

Avo Asatryan
Avo Asatryan

Reputation: 414

i would suggest you the following code:

import re
removed = ""
pattern = re.compile(r'[\.,-]')
with open('your_file', 'r') as f:
    for line in f:
        removed += pattern.sub('',line)

print(removed)

If it is not mandatory to iterate over myList you could use a regular expression.

Upvotes: 0

David Meu
David Meu

Reputation: 1545

Or:

myList = [".", ",", "-"]

with open("my_file.txt") as f:
    f_data = f.read()
    for i in myList:
        f_data = f_data.replace(f'{i}', '')
print(f_data)

Upvotes: 0

bigbounty
bigbounty

Reputation: 17358

f.read() will change the seek position. Hence, you need to store the file contents in a variable

f = open("my_file.txt")

myList = [".", ",", "-"]
f_data = f.read()

for i in myList:
    f_data = f_data.replace(f'{i}', '')

print(f_data)

Upvotes: 2

Related Questions