首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >strip()的Regex版本

strip()的Regex版本
EN

Code Review用户
提问于 2019-07-08 06:22:03
回答 2查看 7.9K关注 0票数 8

这个问题来自于使用Python自动化无聊的东西--第7章。

编写一个函数,该函数接受一个字符串,并执行与strip() string方法相同的操作。如果没有传递除要剥离的字符串以外的其他参数,则将从字符串的开头和结尾移除空格字符。否则,函数的第二个参数中指定的字符将从字符串中删除。

它接受一个字符串和一个字符作为输入,并返回新的剥离字符串。

代码语言:javascript
复制
#regexStrip.py - Regex Version of strip()

import re

def regex_strip(s, char=None):
    """
    Write a function that takes a string and does the same thing as the strip()
    string method. If no other arguments are passed other than the string to
    strip, then whitespace characters will be removed from the beginning and
    end of the string. Otherwise, the characters specified in the second argu-
    ment to the function will be removed from the string.
    """

    if not char:
        strip_left = re.compile(r'^\s*') #string starting with whitespace
        strip_right = re.compile(r'\s*输出:Enter string to be stripped: foo, bar, cat
Enter character to be removed, if none press enter: ,
foo bar cat) #string ending with whitespace

        s = re.sub(strip_left, "", s) #replacing strip_left with "" in string s
        s = re.sub(strip_right, "", s) #replacing strip_right with "" in string s

    else:
        strip_char = re.compile(char)
        s = re.sub(strip_char, "", s)
    return s

if __name__ == '__main__':
    string_to_be_stripped = input("Enter string to be stripped: ")
    char_to_be_removed = input("Enter character to be removed, if none press enter: ")
    print(regex_strip(string_to_be_stripped, char_to_be_removed))        

输出:

A3

EN

回答 2

Code Review用户

发布于 2019-07-08 13:19:01

Pre-compilation

理论上,您需要不止一次地调用这个函数。这意味着您只需要支付一次regex编译的成本,并且应该将re.compile调用移出函数,在模块的全局范围内设置regex变量。

型-暗示

ss: strchar是(我认为)也是char: str

‘从字符串中删除’?

我认为这是需求不明确的错误,但是--如果char参数是字符S从字符串边缘剥离,而不是从字符串中的任何位置删除字符,那就更有意义了。因此,您需要重新评估如何创建regex。

将左、右

合并

不需要两个雷克斯。您可以在捕获组中使用一个:

代码语言:javascript
复制
^\s*(.*?)\s*$
票数 4
EN

Code Review用户

发布于 2019-07-08 16:00:47

使用未经消毒的用户输入,re.compile(char)是危险的。您应该使用re.compile(re.escape(char)),这将允许您从"***Winner***"中删除星号,而不是使用无效的正则表达式崩溃。

另请参阅这个问题和相关答案,以获得对问题意图的不同解释,以删除其他字符。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/223713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档