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

标签 python regex

我正在尝试使用 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

关于python - 使用正则表达式的 Strip() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50055600/

相关文章:

python - 如何根据给定的输入从网络中提取数据到excel?

python - 在 Spotfire 中读取多个值的更快方法

Python 运行速度明显快于 C++?这里似乎有问题

python - 断言 `mock_calls` 等于预期的调用列表

javascript - 正则表达式 - JavaScript

D 中的正则表达式捕获太多

python - 如何从Python中的顺序变量创建数字类别?

java - 使用 Java 的正则表达式类解析数值

regex - 用字符串中的子查询结果替换数字

python - 在python中提取java主类名