I'm trying to recreate the strip()
function of python using Regex. It's the last practice problem from Automate the Boring Stuff with Python. Here's my code:
import re
stripChar = input('Enter character to strip: ')
context = input('Enter string to strip: ')
stripContext = None
def strip(char, string):
if stripChar == "":
regsp = re.compile(r'^\s+|\s+$')
stripContext = regsp.sub("", context)
return stripContext
else:
stripContext = re.sub(r'^(char)+', "", string)
return stripContext
print(strip(stripChar, context))
In line 16, if I replace (char) with any random character, the program is working. However, I can't seem to make a custom variable work there. What am I doing wrong there?
Edit: Stack is saying it's a duplicate of this question. It's not because it' s purely around Regex not only Python.
The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.
The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).
strip will not do what you want. strip removes trailing and leading whitespace. This is simply a matter of string immutability and using string1. replace(' ', '') to solve this problem.
Use the re. sub() method to remove the characters that match a regex from a string, e.g. result = re. sub(r'[! @#$]', '', my_str) .
I slightly changed your script like this,
def strip(char, string):
if char == "": # not "stripChar"
regsp = re.compile(r'^\s+|\s+$')
stripContext = regsp.sub("", string)
return stripContext
else: # some changes are here in this else statement
stripContext = re.sub(r'^{}+|{}+$'.format(char,char), "", strip("",string))
return stripContext
print(strip(stripChar, context))
Output:
Enter character to strip: e
Enter string to strip: efdsafdsaeeeeeeeeee
fdsafdsa
You could do it like this using re.sub
import re
def strip(string, chars=' \n\r\t'):
return re.sub(r'(?:^[{chars}]+)|(?:[{chars}]+$)'.format(chars=re.escape(chars)), '', string)
It uses re.escape
, so users can enter characters like \
and [
that have meaning withing regex strings. It also uses the ^
and $
regex tokens so that only groups of matching characters at the front and end of the string are matched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With