Skip to content

Instantly share code, notes, and snippets.

@j178
Last active September 1, 2017 03:36
Show Gist options
  • Save j178/4b43e797922dad807a3e1fa9d064eac6 to your computer and use it in GitHub Desktop.
Save j178/4b43e797922dad807a3e1fa9d064eac6 to your computer and use it in GitHub Desktop.
Self implemented strip funciton compared to built-in
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