Reputation: 19
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
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
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
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