Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- # Python example of a trim function which removes white
- # space from start and end of a string
- def trim(theString):
- sliceStart = 0;
- sliceEnd = len(theString);
- # Iterate over the list starting at the front
- cntIndex = 0
- while cntIndex < len(theString):
- if theString[cntIndex] != ' ':
- sliceStart = cntIndex
- break
- else:
- cntIndex += 1
- # Iterate over the list starting at the end
- cntIndex = len(theString) - 1
- while cntIndex >= 0:
- if theString[cntIndex] != ' ':
- sliceEnd = cntIndex + 1
- break
- else:
- cntIndex -= 1
- return theString[sliceStart: sliceEnd]
- def regexTrim(theString):
- # Note, performance can be improved by first compiling the regex
- resultString = re.sub("^\s+", "", theString) # Trim Start
- resultString = re.sub("\s+$", "", resultString) # Trim End
- return resultString
- test_1 = " foo";
- test_2 = " bar ";
- test_3 = "baz "
- test_4 = " ba zza "
- test_5 = "blah"
- print("-----Array Operations Tests ------")
- print()
- print("TEST1: '{}': '{}'".format(test_1, trim(test_1)))
- print("TEST2: '{}': '{}'".format(test_2, trim(test_2)))
- print("TEST3: '{}': '{}'".format(test_3, trim(test_3)))
- print("TEST4: '{}': '{}'".format(test_4, trim(test_4)))
- print("TEST5: '{}': '{}'".format(test_5, trim(test_5)))
- print("-----Regex Tests------")
- print()
- print("TEST1: '{}': '{}'".format(test_1, regexTrim(test_1)))
- print("TEST2: '{}': '{}'".format(test_2, regexTrim(test_2)))
- print("TEST3: '{}': '{}'".format(test_3, regexTrim(test_3)))
- print("TEST4: '{}': '{}'".format(test_4, regexTrim(test_4)))
- print("TEST5: '{}': '{}'".format(test_5, regexTrim(test_5)))
- # Notes:
- # ^(\s*)[^\s-]*(\s*)$ This doesn't work, it doesn't match the space in the middle of the word.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement