Skip to main content
 首页 » 编程设计

python之使用正则表达式的 Strip() 函数

2024年09月07日36zhenyulu

我正在尝试使用 Regex 重新创建 python 的 strip() 函数。这是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) 替换为任意随机字符,程序就可以运行。但是,我似乎无法使自定义变量在那里工作。我在那里做错了什么?

编辑:Stack 说它是 this question 的副本.不是因为它' 它纯粹围绕正则表达式而不仅仅是 Python。

请您参考如下方法:

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

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