題目:
寫一個函數,它接受一個字符串,做的事情和 strip()字符串方法一樣。如果只傳入了要去除的字符串,沒有其他參數,那么就從該字符串首尾去除空白字符。否則,函數第二個參數指定的字符將從該字符串中去除。
分析:
Python 支持格式化字符串的輸出 。盡管這樣可能會用到非常復雜的表達式,但最基本的用法是將一個值插入到一個有字符串格式符 %s 的字符串中。
在 Python 中,字符串格式化使用與 C 中 sprintf 函數一樣的語法。
如下實例:
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 = re.compile(t_format)
s = s_re.sub('',s)
return s
print(re_strip('aadasdfsaaa','a'))
print(re_strip(' dafsdfa sadfasd '))
運行結果
dasdfs
dafsdfa sadfasd