python实践项目七:正则表达式版本的strip()函数

描述写一个函数,它接受一个字符串,做的事情和 strip()字符串方法一样。如果只传入了要去除的字符串, 没有其他参数, 那么就从该字符串首尾去除空白字符;否则, 函数第二个参数指定的字符将从该字符串中去除。

注意:strip()字符串方法将返回一个新的字符串, 它的开头或末尾都没有空白字符。lstrip()和 rstrip()方法将相应删除左边或右边的空白符。
代码
 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 import re
 4 
 5 def strip(text, chars=None):
 6     """去除首尾的字符
 7     :type text: string
 8     :type chars: string
 9     :rtype: string
10     """
11     if chars is None:
12         reg = re.compile('^ *| *$')
13     else:
14         reg = re.compile(r'^[' + chars + ']*|[' + chars + ']*$')
15     return reg.sub('', text) #把text里符合reg格式的字符串替换成'',也即去掉该字符串
16 
17 print(strip('   123456   '))  # 123456
18 print(strip('   123456'))  # 123456
19 print(strip('   123456    '))  # 123456
20 print(strip('123456   654321'))  # 123456   654321
21 print(strip('123456   654321', '1'))  # 23456   65432
22 print(strip('123456   654321', '1234'))  # 56   65
23 print(strip('123456   654321', '124'))  # 3456   6543

运行结果

 

posted on 2019-07-05 17:57  白居不易1101  阅读(1373)  评论(0编辑  收藏  举报