Advertisement
Guest User

Untitled

a guest
May 6th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import re
  2. # Python example of a trim function which removes white
  3. # space from start and end of a string
  4.  
  5. def trim(theString):
  6.  
  7. sliceStart = 0;
  8. sliceEnd = len(theString);
  9.  
  10. # Iterate over the list starting at the front
  11. cntIndex = 0
  12. while cntIndex < len(theString):
  13. if theString[cntIndex] != ' ':
  14. sliceStart = cntIndex
  15. break
  16. else:
  17. cntIndex += 1
  18.  
  19. # Iterate over the list starting at the end
  20. cntIndex = len(theString) - 1
  21. while cntIndex >= 0:
  22. if theString[cntIndex] != ' ':
  23. sliceEnd = cntIndex + 1
  24. break
  25. else:
  26. cntIndex -= 1
  27.  
  28. return theString[sliceStart: sliceEnd]
  29.  
  30.  
  31. def regexTrim(theString):
  32. # Note, performance can be improved by first compiling the regex
  33. resultString = re.sub("^\s+", "", theString) # Trim Start
  34. resultString = re.sub("\s+$", "", resultString) # Trim End
  35. return resultString
  36.  
  37.  
  38. test_1 = " foo";
  39. test_2 = " bar ";
  40. test_3 = "baz "
  41. test_4 = " ba zza "
  42. test_5 = "blah"
  43.  
  44. print("-----Array Operations Tests ------")
  45. print()
  46. print("TEST1: '{}': '{}'".format(test_1, trim(test_1)))
  47. print("TEST2: '{}': '{}'".format(test_2, trim(test_2)))
  48. print("TEST3: '{}': '{}'".format(test_3, trim(test_3)))
  49. print("TEST4: '{}': '{}'".format(test_4, trim(test_4)))
  50. print("TEST5: '{}': '{}'".format(test_5, trim(test_5)))
  51.  
  52. print("-----Regex Tests------")
  53. print()
  54. print("TEST1: '{}': '{}'".format(test_1, regexTrim(test_1)))
  55. print("TEST2: '{}': '{}'".format(test_2, regexTrim(test_2)))
  56. print("TEST3: '{}': '{}'".format(test_3, regexTrim(test_3)))
  57. print("TEST4: '{}': '{}'".format(test_4, regexTrim(test_4)))
  58. print("TEST5: '{}': '{}'".format(test_5, regexTrim(test_5)))
  59.  
  60.  
  61. # Notes:
  62. # ^(\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