0

I am trying to erase all question marks('?') from a .txt file. I tried tokenizing all content and printing it back like this:

with open('my.txt', 'r') as f:
  tokenized = f.split()
for i in len(tokenized):
  if tokenized[i] == '?':
    tokenized.remove('?')
with open('my.txt', 'w') as f:
    f.write(' '.join(tokenized))

but it doesn't remove all question marks and if there are any line breaks or whitespace longer than 1 it removes them.

kaiserthe13th
  • 27
  • 1
  • 7

2 Answers2

2
with open("my.txt", "r") as f:
    content = f.read().split("?")
with open("my.txt", "w") as f:
    f.write("".join(content))

You can also use replace.

Jeeva
  • 1,029
  • 3
  • 15
  • 21
0

You can use string.replace for that:

with open('my.txt', 'r') as f:
  content = f.read()

with open('my.txt', 'w') as f:
    f.write(content.replace('?', ''))

The issue with your solution is that you use string.split without any argument for separator. By default, it will target any whitespace (including newlines or multiple whitespaces). But you join only by one whitespace, so the end result can be different.

KiraLT
  • 2,385
  • 1
  • 24
  • 36