写一个函数,它接受一个字符串,做的事情和strip()字符串方法一样。如果只传入了要去除的字符串,没有其他参数,那么就从该字符串首尾去除空白字符。否则,函数第二个参数指定的字符将从该字符串中去除。
在网上查了两个答案都用到了%不太明白怎么用,而且都是用了re.sub()的函数,如果书后习题用本书没讲的东西来解决就失去了练习的意义了对吧,所以我还是研究了一下用书中教的对表达式用.sub()的方法。
而且实现了传入第二个参数后,不仅删去指定的字符,同时实现默认的去掉首位空白的功能。
import re
def new_strip(text, str=''):
if str:
pattern_1 = re.compile(str)
temp_text = pattern_1.sub('',text) #先删掉指定字符
pattern_2 = re.compile(r'^\s*(.*)\s*$')
new_text = pattern_2.sub(r'\1',temp_text) #再删掉两端空白
else:
pattern = re.compile(r'^\s*(.*)\s*$')
new_text = pattern.sub(r'\1',text)
return new_text
运行函数:
text = str(input('Input string: '))
new_text = new_strip(text, 'e') #可以指定一个字符比如e,或者不传入第二个参数
print(new_text)