Replace and overwrite instead of appending

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace: The other way is to read the file then open it again with open(myfile, ‘w’): Neither truncate nor open(…, ‘w’) will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4). By the way, this … Read more

Best way to replace multiple characters in a string?

Replacing two characters I timed all the methods in the current answers along with one extra. With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace(‘&’, ‘\&’).replace(‘#’, ‘\#’). Timings for each function: a) 1000000 loops, best of 3: 1.47 μs per … Read more

How can I remove a character from a string using JavaScript?

I am so close to getting this, but it just isn’t right. All I would like to do is remove the character r from a string. The problem is, there is more than one instance of r in the string. However, it is always the character at index 4 (so the 5th character). Example string: crt/r2002_2 What I want: crt/2002_2 This … Read more

Best way to replace multiple characters in a string?

Replacing two characters I timed all the methods in the current answers along with one extra. With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace(‘&’, ‘\&’).replace(‘#’, ‘\#’). Timings for each function: a) 1000000 loops, best of 3: 1.47 μs per … Read more