python - 使用正则表达式的 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。
解决方案
我像这样稍微改变了你的脚本,
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 - 如何在python中获取单击和拖动事件的光标位置?
- php - Laravel - 控制器看不到图像输入
- python - 如何使用 python imaplib 阅读电子邮件
- f# - F# 中的尾递归程序
- php - 无法从 PHP 中的 AJAX 响应中获取数据
- node.js - 带节点的 Nginx 代理。在端口 80 上运行时奇怪的重写
- r - R中数据框中每行最大值的比率
- javascript - RxJs - 创建 Observable 的 Observable 数组的正确模式/方法是什么?
- r - nflscrapR 包的安装问题
- flutter - 如何在 Flutter 中共享卡片?