Python实践练习:strip()的正则表达式版本
题⽬:
写⼀个函数,它接受⼀个字符串,做的事情和 strip()字符串⽅法⼀样。如果只传⼊了要去除的字符串,没有其他参数,那么就从该字符串⾸尾去除空⽩字符。否则,函数第⼆个参数指定的字符将从该字符串中去除。
分析:
Python ⽀持格式化字符串的输出。尽管这样可能会⽤到⾮常复杂的表达式,但最基本的⽤法是将⼀个值插⼊到⼀个有字符串格式符 %s 的字符串中。
在 Python 中,字符串格式化使⽤与 C 中 sprintf 函数⼀样的语法。
python正则表达式判断
如下实例:
print "My name is %s and weight is %d kg!" % ('Zara', 21)
以上实例输出结果:
My name is Zara and weight is 21 kg!
代码
import re
def re_strip(s, t=r'\s'):
t_format = r'^%s*|%s*$' % (t, t)
s_re = repile(t_format)
s = s_re.sub('',s)
return s
print(re_strip('aadasdfsaaa','a'))
print(re_strip('  dafsdfa sadfasd  '))
运⾏结果
dasdfs
dafsdfa sadfasd