0

I have a text file that contains the following data:

't''h''i''s''i''s''a''t''e''s''t''f''o''r''s''t''a''c''k''o''v''e''r''f''l''o''w'

I want to read the file, and remove all 's so the final result will look like this:

thisisatestforstackoverflow

I don't know if you need to write to another file or you can just change the current one, but I have tried to do it with replace() and I couldn't get it to work. If someone could write a small peace of code to show me how it works I will appreciate it!

Graham
  • 3,153
  • 3
  • 16
  • 31
yarinc
  • 41
  • 2
  • 9

3 Answers3

3

I like having these utility functions around:

def string_to_file(string, path):
    with open(path, 'w') as f:
        f.write(string)


def file_to_string(path):
    with open(path, 'r') as f:
        return f.read()

With those, the answer becomes:

string_to_file(file_to_string(path).replace("'", ""), path)
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • You would really like Python's pathlib [`read_text`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_text) and `write_text` methods. – Ben Nov 04 '18 at 22:45
1
import re 
string = 't''h''i''s''i''s''a''t''e''s''t''f''o''r''s''t''a''c''k''o''v''e''r''f''l''o''w'
s = re.findall(r"[^']", string)

This will return a list:

C:\Users\Documents>py test.py
['t', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 's', 't', 'f', 'o', 'r', 's', 't', 'a', 'c', 'k', 'o', 'v', 'e', 'r', 'f', 'l', 'o', 'w']

and you can do anything with it.
Like:

''.join(s)

output:

C:\Users\Documents>py test.py
thisisatestforstackoverflow
Rarblack
  • 4,559
  • 4
  • 22
  • 33
0

here is you answer:

str = 't''h''i''s''i''s''a''t''e''s''t''f''o''r''s''t''a''c''k''o''v''e''r''f''l''o''w'
str.replace("'", "")
print(str)
Saeed Heidari
  • 411
  • 4
  • 8
  • This answer isn't responsive to the OP's request to take data from a file (i.e. it doesn't start as a string). Ignoring that, oddly enough, your first line here is sufficient to stand alone: Python parses that statement into the single string `'thisisatestforstackoverflow'` automatically, for reasons I can't fathom. – Michael MacAskill Nov 04 '18 at 22:13
  • In case of taking data from file just convert it line by line to string and do so. – Saeed Heidari Nov 04 '18 at 22:58
  • fd = open(filename, 'rU') chars = [] for line in fd: line = str(line) line.replace("'", "") – Saeed Heidari Nov 04 '18 at 22:58