我正在尝试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))
Run Code Online (Sandbox Code Playgroud)
在第 16 行,如果我用任何随机字符替换 (char),则程序正在运行。但是,我似乎无法在那里创建自定义变量。我在那里做错了什么?
编辑:堆栈说它是这个问题的重复。这不是因为它纯粹是围绕 Regex 而不仅仅是 Python。