首页 > 解决方案 > 使用正则表达式的 Strip() 函数

问题描述

我正在尝试strip()使用正则表达式重新创建 python 的功能。这是Automate the Boring Stuff with Python的最后一道练习题。这是我的代码:

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))

在第 16 行,如果我将 (char) 替换为任何随机字符,则程序正在运行。但是,我似乎无法使自定义变量在那里工作。我在那里做错了什么?

编辑:堆栈说它是这个问题的副本。这不是因为它完全围绕正则表达式而不仅仅是 Python。

标签: pythonregex

解决方案


我像这样稍微改变了你的脚本,

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))

输出:

Enter character to strip: e
Enter string to strip:   efdsafdsaeeeeeeeeee
fdsafdsa

推荐阅读