Last active
September 1, 2017 03:36
-
-
Save j178/4b43e797922dad807a3e1fa9d064eac6 to your computer and use it in GitHub Desktop.
Self implemented strip funciton compared to built-in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from string import whitespace | |
import timeit | |
def strip(string, chars=whitespace): | |
if not isinstance(string, (str, bytes)) \ | |
or not isinstance(chars, type(string)): | |
raise ValueError | |
left = 0 | |
for left, s in enumerate(string): | |
if s not in chars: | |
break | |
right = 0 | |
for right, s in enumerate(reversed(string)): | |
if s not in chars: | |
break | |
return string[left:len(string) - right] | |
def test(): | |
print('self', timeit.timeit(r"strip('\t\nabc ')", globals=globals())) | |
print('builtin', timeit.timeit(r"'\t\nabc '.strip()")) | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment