首页 > 编程语言 > 详细

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

时间:2019-07-05 18:53:01      阅读:115      评论:0      收藏:0      [点我收藏+]

描述写一个函数,它接受一个字符串,做的事情和 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

运行结果

技术分享图片

 

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

原文:https://www.cnblogs.com/heyangblog/p/11139868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!