Posts

Showing posts with the label Case Insensitive

Case-insensitive String Startswith In Python

Answer : You could use a regular expression as follows: In [33]: bool(re.match('he', 'Hello', re.I)) Out[33]: True In [34]: bool(re.match('el', 'Hello', re.I)) Out[34]: False On a 2000-character string this is about 20x times faster than lower() : In [38]: s = 'A' * 2000 In [39]: %timeit s.lower().startswith('he') 10000 loops, best of 3: 41.3 us per loop In [40]: %timeit bool(re.match('el', s, re.I)) 100000 loops, best of 3: 2.06 us per loop If you are matching the same prefix repeatedly, pre-compiling the regex can make a large difference: In [41]: p = re.compile('he', re.I) In [42]: %timeit p.match(s) 1000000 loops, best of 3: 351 ns per loop For short prefixes, slicing the prefix out of the string before converting it to lowercase could be even faster: In [43]: %timeit s[:2].lower() == 'he' 1000000 loops, best of 3: 287 ns per loop Relative timings of these approaches will of course depe...

Case Insensitive Argparse Choices

Answer : Transform the argument into lowercase by using type = str.lower for the -p switch. This solution was pointed out by chepner in a comment. The solution I proposed earlier was type = lambda s : s.lower() which is also valid, but it's simpler to just use str.lower . Using lower in the type is nice way of doing this, if you don't mind loosing the case information. If you want to retain the case, you could define a custom choices class. The choices needs two methods, __contains__ (for testing in ), and iteration (to list the choices). class mylist(list): # list subclass that uses lower() when testing for 'in' def __contains__(self, other): return super(mylist,self).__contains__(other.lower()) choices=mylist(['win64','win32']) parser = argparse.ArgumentParser() parser.add_argument("-p", choices=choices) print(parser.parse_args(["-p", "Win32"])) # Namespace(p='Win32') The ...