Is there an easier way to replace multiple different things at once

im trying to use the .replace() mutiple times at once and i was wondering if there was a cleaner way to do it

Code example:

with open("user_data.txt", "w") as f:
    f.write(str(user_data).replace("{","{\n").replace("}","\n}").replace(",",",\n"))
    f.close()

the code works fine but looks a bit messy

1 Like

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)

If you’re working on JSON data, you’ve just been lucky, not fine.

There isn’t a provided method to perform a sequence of replacements, but
nothing prevents you writing a small function, eg:

def multireplace(s, *replacements):
    for src, subst in replacements:
        s = s.replace(src, subst)
    return s

and then just calling that. That’s what programing is for.

If, as I suspect, you’re trying to make JSON more readable I strongly
recommend that you use the standard json module to parse the JSON, and
to write it out again with your preferred delimters (see the docs).
Otherwise you run al sorts of risks around having your replacement
strings as part of the data, for example strings containing curly
brackets.

Cheers,
Cameron Simpson cs@cskk.id.au

I did consider specializing my answer, but it didn’t fully occur to me (since the output file had the .txt extension, and there weren’t a ton of obvious clues to go on) that this might be more of a true XY problem.

It seems you’re outputting a dictionary to a file; instead of the above naive approach, just use json.dumps (possibly with a few formatting options). This will output your dictionary in a format that is not only human readable, but also very easily machine-readable to, such that virtually anything can read it in and do more things with it.

Also, be sure to specify the encoding of your output file; it almost any likely case it should be utf-8 (not the default locale-dependent one). And, to note, f.close() is entirely redundant, since the whole purpose of the with block is to close your file when you’re done.

So, the entirety of the above can be replaced by (including pretty-printing with indent levels, unlike the original):

import json
with open("user_data.json", "w", encoding="utf-8") as f:
    json.dump(user_data, f, indent=4)