使用正则表达式复刻Python的strip()函数问题求助
Fixing Your Regex-Based
strip() Implementation Let's break down what's going wrong with your code and fix it up to match Python's built-in strip() behavior. You've got the right idea using regex, but there are a few small but critical issues:
Key Problems in Your Current Code
- Ignoring function parameters: Your
stripfunction acceptscharandstringarguments, but inside the function you're using the globalstripCharandcontextvariables instead. That means the function doesn't actually use the values you pass to it when calling it! - Literal "char" in regex: When you use
r'^(char)+', the regex is looking for the literal string "char" at the start of the input, not the actual character the user entered. You need to dynamically insert the user's character into the pattern. - Only stripping from the start: Python's
strip()removes characters from both the beginning and end of the string, but your current code only handles the start. - Unused variables: The
stripContext = Noneline outside the function does nothing, and you can simplify the code by returning the regex result directly instead of assigning it to a variable first.
Corrected Code
import re def strip(char, string): if char == "": # Handle default case: strip whitespace from start and end whitespace_regex = re.compile(r'^\s+|\s+$') return whitespace_regex.sub("", string) else: # Escape the input character to handle regex special characters (like ., *) escaped_char = re.escape(char) # Regex to match the character at start OR end of the string custom_regex = re.compile(rf'^({escaped_char})+|({escaped_char})+$') return custom_regex.sub("", string) # Get user input strip_char = input('Enter character to strip: ') input_string = input('Enter string to strip: ') # Run the function and display the result print(strip(strip_char, input_string))
What Changed?
- Proper parameter usage: The function now uses the
charandstringparameters directly, so it works as expected when called with user input. - Escaped custom characters:
re.escape(char)ensures that if the user inputs a regex special character (like.or+), it's treated as a regular character instead of a regex wildcard. - Dual-end stripping: The regex
rf'^({escaped_char})+|({escaped_char})+$'uses the|operator to match one or more of the custom characters at either the start (^) or end ($) of the string. - Cleaner return logic: We return the result of
sub()directly instead of storing it in an intermediate variable, making the code more concise.
Test Examples
- If you enter
strip_char = "x"andinput_string = "xxHello Worldxx", the output will be"Hello World". - If you leave
strip_charempty and enter" Python is fun! ", the output will be"Python is fun!"(just like the built-instrip()).
内容的提问来源于stack exchange,提问作者ahmed_imtiaz
相关产品推荐
相关产品推荐

