I'm trying to run the method below against a very large corpus and I need to optimize/reduce the run time for this method as it already takes up about 6 seconds to execute.Requirements:Check the word only consist of alphabets, hyphen and apostropheFirst character of word must be alphabetLast character of word must be alphabet or apostrophe onlyUse of re library (regex) strictly not alloweddef delUnknownChar(w):    wf = []    for c in w:        if (c == ' or c == - or c.isalpha()):            wf.append(c)    w = .join(wf)    wf.clear()    if (len(w) > 1):        while(not w[0].isalpha()):            w = w[1:]        while (w[-1] == -):            w = w[:-1]        return w    else:        return Nonestring1 = delUnknownChar(-'test'-)print(string1)Output will be test'The code above will take about 5 seconds to run.If I change lines 2-7 of the code to this line:w = .join(c for c in w if c == ' or c == - or c.isalpha())The runtime somehow increases by 1 more second.Does anyone here have a better idea or an improved optimized way to check for this at a much faster speed?
Optimise runtime of filter character method
python;performance;strings