import res = "ttthis line has two tabs of indention"re.match(r"s*", s).group()// "tt"s = " this line has four spaces of indention"re.match(r"s*", s).group()// " "
要删除前导空格,请使用lstrip。
由于反对票可能会质疑正则表达式的效率,因此我进行了一些分析以检查每种情况的效率。
字符串很长,引导空间很短
正则表达式> Itertools >> lstrip
>>> timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"s*")s=" hello world!"*10000', number=100000)0.10037684440612793>>> timeit.timeit('"".join(itertools.takewhile(lambda x:x.isspace(),s))', 'import itertools;s=" hello world!"*10000', number=100000)0.7092740535736084>>> timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s=" hello world!"*10000', number=100000)0.51730513572692871>>> timeit.timeit('s[:-len(s.lstrip())]', 's=" hello world!"*10000', number=100000)2.6478431224822998字符串很短,前导空间很短
lstrip> RegEx> Itertools
如果您可以将字符串的长度限制为不超过千个字符,则lstrip技巧可能会更好。
>>> timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"s*");s=" hello world!"*100', number=100000)0.099548101425170898>>> timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s=" hello world!"*100', number=100000)0.53602385520935059>>> timeit.timeit('s[:-len(s.lstrip())]', 's=" hello world!"*100', number=100000)0.064291000366210938这显示lstrip技巧的缩放比例大致为O(√n),并且如果前导空格的数量不是很多,则RegEx和itertool方法为O(1)。
字符串很短,前导空间很长
lstrip >> RegEx >>> Itertools
如果前导空格很多,请不要使用RegEx。
>>> timeit.timeit('s[:-len(s.lstrip())]', 's=" "*2000', number=10000)0.047424077987670898>>> timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"s*");s=" "*2000', number=10000)0.2433168888092041>>> timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s=" "*2000', number=10000)3.9949162006378174字符串很长,引导空间很长
lstrip >>> RegEx >>>>>>>> Itertools
>>> timeit.timeit('s[:-len(s.lstrip())]', 's=" "*200000', number=10000)4.2374031543731689>>> timeit.timeit('r.match(s).group()', 'import re;r=re.compile(r"s*");s=" "*200000', number=10000)23.877214908599854>>> timeit.timeit('"".join(itertools.takewhile(str.isspace,s))', 'import itertools;s=" "*200000', number=100)*100415.72158336639404如果非空间部分不是很多,这表明所有方法的缩放比例大致为O(m)。



