Modifying a string multiple times based on dict

Viewed 56

Minimal example:

Code

s = "A or B and C"
d = {"A": "1", "B": "0", "C": "0"}

for key, value in d.items():
    s = s.replace(key, value)

print(s)

Output

1 or 0 and 0

This code produces the desired output, i do however feel like there is a clever one-liner that can replace my loop.

1 Answers

Although I'd recommend just keeping your code as it is:

s = "A or B and C"
d = {"A": "1", "B": "0", "C": "0"}

print(s.translate(s.maketrans(d)))

Output:

1 or 0 and 0
Related