这个问题来自于使用Python自动化无聊的东西--第7章。
编写一个函数,该函数接受一个字符串,并执行与strip() string方法相同的操作。如果没有传递除要剥离的字符串以外的其他参数,则将从字符串的开头和结尾移除空格字符。否则,函数的第二个参数中指定的字符将从字符串中删除。
它接受一个字符串和一个字符作为输入,并返回新的剥离字符串。
#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
发布于 2019-07-08 13:19:01
理论上,您需要不止一次地调用这个函数。这意味着您只需要支付一次regex编译的成本,并且应该将re.compile调用移出函数,在模块的全局范围内设置regex变量。
s是s: str,char是(我认为)也是char: str。
我认为这是需求不明确的错误,但是--如果char参数是字符S从字符串边缘剥离,而不是从字符串中的任何位置删除字符,那就更有意义了。因此,您需要重新评估如何创建regex。
合并
不需要两个雷克斯。您可以在捕获组中使用一个:
^\s*(.*?)\s*$发布于 2019-07-08 16:00:47
使用未经消毒的用户输入,re.compile(char)是危险的。您应该使用re.compile(re.escape(char)),这将允许您从"***Winner***"中删除星号,而不是使用无效的正则表达式崩溃。
另请参阅这个问题和相关答案,以获得对问题意图的不同解释,以删除其他字符。
https://codereview.stackexchange.com/questions/223713
复制相似问题