title: Regex replacement for strip()
body: <p>Long time/first time.</p>
  
  <p>I am a pharmacist by trade by am going through the motions of teaching myself how to code in a variety of languages that are useful to me for things like task automation at work, but mainly Python 3.x. I am working through the automatetheboringstuff eBook and finding it great. </p>
  
  <p>I am trying to complete one of the practice questions from Chapter 7:
  <em>"Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string."</em></p>
  
  <p>I am stuck for the situation when the characters I want to strip appear in the string I want to strip them from e.g. 'ssstestsss'.strip(s)</p>
  
  <pre class="lang-python prettyprint-override"><code>#!python3
  import re
  
  respecchar = ['?', '*', '+', '{', '}', '.', '\\', '^', '$', '[', ']']
  
  
  def regexstrip(string, _strip):
      if _strip == '' or _strip == ' ':
          _strip = r'\s'
      elif _strip in respecchar:
          _strip = r'\'+_strip'
      print(_strip) #just for troubleshooting 
      re_strip = re.compile('^'+_strip+'*(.+)'+_strip+'*$')
      print(re_strip) #just for troubleshooting 
      mstring = re_strip.search(string)
      print(mstring) #just for troubleshooting 
      stripped = mstring.group(1)
      print(stripped)
  </code></pre>
  
  <p>As it is shown, running it on ('ssstestsss', 's') will yield 'testsss' as the .+ gets all of it and the * lets it ignore the final 'sss'. If I change the final * to a + it only improves a bit to yield 'testss'. If I make the capture group non-greedy (i.e. (.+)? ) I still get 'testsss' and if exclude the character to be stripped from the character class for the capture group and remove the end string anchor (i.e. <code>re.compile('^'+_strip+'*([^'+_strip+'.]+)'+_strip+'*')</code> I get 'te' and if I don't remove the end string anchor then it obviously errors. </p>
  
  <p>Apologies for the verbose and ramble-y question. </p>
  
  <p>I deliberately included all the code (work in progress) as I am only learning so I realise that my code is probably rather inefficient, so if you can see any other areas where I can improve my code, please let me know. I know that there is no practical application for this code, but I'm going through this as a learning exercise. </p>
  
  <p>I hope I have asked this question appropriately and haven't missed anything in my searches. </p>
  
  <p>Regards</p>
  
  <p>Lobsta</p>