On a high level, the method you’ve demonstrated is both idiomatic and the fastest (or one at least one of them). However, a bit of reorganization will make it both a little more efficient (by not leaving the file handle open as long), and will ensure it looks cleaner and more readable. Specifically, pull the replace operation outside the with
block (as the latter is not really relevant to the core question anyway) and put each replace on its own line. So, you could do something like:
user_data_out = (
user_data
.replace("{","{\n")
.replace("}","\n}")
.replace(",",",\n")
# Etc.
)
with open("user_data.txt", "w") as f:
f.write(user_data_out)
f.close()
Another option, if you’re only dealing with replacing single characters in the input string, is str.translate coupled with str.maketrans, but unless you’re doing a lot of replacements, its probably overkill, and is less well known and idiomatic. It would look like this:
output_replacements = {
"{": "{\n",
"]": "\n}",
",", ",\n",
# Etc.
)
user_data_out = user_data.translate(str.maketrans(output_replacements))
You may also be able to use a more specific solution to your specific task, such as e.g. adding line breaks after specific characters. For example, to add line breaks after {
and ,
, you could do so with regex:
import re
user_data_out = re.sub("([{,])", "\\1\n", user_data)