Skip to content

Instantly share code, notes, and snippets.

@mekuls
Last active May 6, 2016 11:39
Show Gist options
  • Save mekuls/9887b5add0cba1e88a402f1ec42927b6 to your computer and use it in GitHub Desktop.
Save mekuls/9887b5add0cba1e88a402f1ec42927b6 to your computer and use it in GitHub Desktop.
A small gist that toys with trimming a string
import re
def regexTrim(theString):
# Neat little trim function that uses expressions and replace/substring
resultString = re.sub("^\s+", "", theString) # Trim Start
resultString = re.sub("\s+$", "", resultString) # Trim End
return resultString
def trim(theString):
# Algorithm that does what it's supposed to
sliceStart = 0;
sliceEnd = len(theString);
# Front to back, break on non space char
cntIndex = 0
while cntIndex < len(theString):
if theString[cntIndex] != ' ':
sliceStart = cntIndex
break
else:
cntIndex += 1
# Back to front, break on non space char
cntIndex = len(theString) - 1
while cntIndex >= 0:
if theString[cntIndex] != ' ':
sliceEnd = cntIndex + 1
break
else:
cntIndex -= 1
return theString[sliceStart: sliceEnd]
tests = {
# String: Expected
" foo": "foo",
" bar ": "bar",
"baz ": "baz",
" ba zza ": "ba zza",
"blah": "blah",
"": ""
}
print("-----Array Operations Tests ------")
for key in tests:
trimmed = trim(key)
if trimmed == tests[key]:
result = "PASS"
else:
result = "FAIL - expected {}".format(tests[key])
print("TEST: '{}': '{}' {}".format(key, trim(key), result))
print("-----Regex Tests------")
for key in tests:
trimmed = trim(key)
if trimmed == tests[key]:
result = "PASS"
else:
result = "FAIL - expected {}".format(tests[key])
print("TEST: '{}': '{}' {}".format(key, regexTrim(key), result))
# Notes:
# ^(\s*)[^\s-]*(\s*)$ This doesn't work, it doesn't match the space in the middle of the word.
# Neither does ^\s*(.+)\s*$ because the (.+) in the middle also matches that space at the end.
# Output:
#-----Array Operations Tests ------
#TEST: '': '' PASS
#TEST: 'baz ': 'baz' PASS
#TEST: 'blah': 'blah' PASS
#TEST: ' ba zza ': 'ba zza' PASS
#TEST: ' bar ': 'bar' PASS
#TEST: ' foo': 'foo' PASS
#-----Regex Tests------
#TEST: '': '' PASS
#TEST: 'baz ': 'baz' PASS
#TEST: 'blah': 'blah' PASS
#TEST: ' ba zza ': 'ba zza' PASS
#TEST: ' bar ': 'bar' PASS
#TEST: ' foo': 'foo' PASS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment