I want to replace repeated instances of the \"*\"
character within a string with a single instance of \"*\"
. For example if the string is \"*
I timed all the methods in the current answers (with Python 3.7.2, macOS High Sierra).
b()
was the best overall, c()
was best when no matches are made.
def b(text):
re.sub(r"\*\*+", "*", text)
# aka squeeze()
def c(text):
while "*" * 2 in text:
text = text.replace("*" * 2, "*")
return text
Input 1, no repeats:
'a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*'
Input 2, with repeats:
'a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*****************************************************************************************************a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*'
The methods:
#!/usr/bin/env python
# encoding: utf-8
"""
See which function variants are fastest. Run like:
python -mtimeit -s"import time_functions;t='a*'*100" "time_functions.a(t)"
python -mtimeit -s"import time_functions;t='a*'*100" "time_functions.b(t)"
etc.
"""
import re
def a(text):
return re.sub(r"\*+", "*", text)
def b(text):
re.sub(r"\*\*+", "*", text)
# aka squeeze()
def c(text):
while "*" * 2 in text:
text = text.replace("*" * 2, "*")
return text
regex = re.compile(r"\*+")
# like a() but with (premature) optimisation
def d(text):
return re.sub(regex, "*", text)
def e(text):
return "".join(c for c, n in zip(text, text[1:] + " ") if c + n != "**")
def f(text):
while True:
if "**" in text: # if two stars are in the variable pattern
text = text.replace("**", "*") # replace two stars with one
else: # otherwise
break # break from the infinite while loop
return text