(Jun-18-2022, 02:24 PM)DPaul Wrote: String.replace() is not "just" faster, it is 45 times faster than regex.I most cases it dos not matter at all,if run one time will never feel the difference.
(Jun-18-2022, 02:24 PM)DPaul Wrote: Are you challenging me to beat regex in doing these replacements?You can try i did a test just now and it did not look good with replace(need many calls).
Then a surprise need to this with more strings.
As you see regex has no problem as the pattern will work for many different scenarios,
with replace has to start from scratch on the new string.
import re #target_str = "Jessa Knows Testing And Machine Learning \t \n" target_str = "Paul Knows Testing And Machine Learning\n\t \n" res_str = re.sub(r"\s+", " ", target_str) print(res_str)
Output:Paul Knows Testing And Machine Learning