You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用正则表达式复刻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 strip function accepts char and string arguments, but inside the function you're using the global stripChar and context variables 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 = None line 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?

  1. Proper parameter usage: The function now uses the char and string parameters directly, so it works as expected when called with user input.
  2. 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.
  3. 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.
  4. 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" and input_string = "xxHello Worldxx", the output will be "Hello World".
  • If you leave strip_char empty and enter " Python is fun! ", the output will be "Python is fun!" (just like the built-in strip()).

内容的提问来源于stack exchange,提问作者ahmed_imtiaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:58:33