Q:

Python: .strip() and .write() seem to produce whitespace

I wrote some code to let me type special characters without learning the commands for them so I wrote this:
file = open('test.txt', 'r+')
text = file.read()

text = text.replace('//a', 'Ä')
text = text.replace('//o', 'Ö')
text = text.replace('//u', 'Ü')

text = text.replace('/a', 'ä')
text = text.replace('/o', 'ö')
text = text.replace('/u', 'ü')

text = text.replace('/s', 'ß')

file.truncate(0) # Clears the file
file.write(text.strip()) # edit was .strip(''), made no diffence 
print(text)

An example input would be 'n/achtes' which would become 'nächtes'
This sort of works but when I run the file I get a huge amount of blank space in the text file for example 'n/achtes' turns into:
 '        nächtes'

If I run the program a second time the output, on sublimetext 3, ends with nächtes but has 8 uncopyable copies of <0x00> in a different colour. The amount of blank spaces increases as well in the text file.

A:

truncate(0) resizes the file to zero size, but the current position is not changed.
When writing the data, it is written at current position, so the rest of the file gets null bytes to "pad".
It is a better practice to use truncate() without parameter to truncate the file in the current position:
f.seek(0)    # go to the beginning of the file
f.truncate() # truncate in current position

