【发布时间】:2021-11-19 19:46:03
【问题描述】:
我正在尝试使用正则表达式重新创建 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) 替换为任何随机字符,则程序正在运行。但是,我似乎无法让自定义变量在那里工作。我在那里做错了什么?
编辑:堆栈说它是this question 的副本。不是因为它' s 纯粹围绕正则表达式而不仅仅是 Python。
【问题讨论】:
-
你能添加任何样本输入和o/p吗?
-
您指的不是变量。
"char"是四个字符的文字字符串,而不是同名变量的值。考虑学习如何使用.format()。附带说明一下,如果您不多次使用它,那么编译狂欢是没有意义的。