Home >Backend Development >Python Tutorial >How to Efficiently Replace Multiple Characters in a String?
Original Question:
How can I efficiently replace multiple characters in a string, such as & -> &, # -> #, etc.?
While the provided code works, it involves multiple sequential replacements, which may be inefficient.
strs = strs.replace('&', '\&') strs = strs.replace('#', '\#') ...
A more efficient approach is to chain together the replacements.
text.replace('&', '\&').replace('#', '\#')
Test: Replace the characters & and # in the string abc&def#ghi.
Method | Time (μs per loop) |
---|---|
Chaining replacements | 0.814 |
Various other methods are available for replacing characters in a string:
import re rx = re.compile('([&#])') text = rx.sub(r'\', text)
def mk_esc(esc_chars): return lambda s: ''.join(['\' + c if c in esc_chars else c for c in s]) esc = mk_esc('&#') text = esc(text)
chars = "&#" for c in chars: text = text.replace(c, "\" + c)
Instead of checking for the existence of each character in the input string, use an iterator to loop through the characters to be replaced. This can significantly improve performance.
Python 3 outperforms Python 2 in character replacement tasks due to its faster string manipulation capabilities.
The above is the detailed content of How to Efficiently Replace Multiple Characters in a String?. For more information, please follow other related articles on the PHP Chinese website!