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

本文介绍了一个自定义的strip函数,该函数模仿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

运行结果

 

转载于:https://www.cnblogs.com/heyangblog/p/11139868.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值