Python模拟删除字符串两边的空白

目标:
  1.使用string模块的whitespace
  2.删除左边、右边以及两边的空白

代码如下:

[root@localhost python]# cat rmspace.py

#!/usr/bin/env python
#coding:utf8
"""
使用字符串删除左右两端的空白。
"""

from string import whitespace

#删除左边的空白
def lrmsps(astr):
    for i in xrange(len(astr)):
        if astr[i] not in whitespace:
            return astr[i:]
    #当输入的全是空白字符时,返回空
    return ''

#删除右边的空白,从列表的右边开始判断
def rrmsps(astr):
    for i in reversed(xrange(len(astr))):
        if astr[i] not in whitespace:
            return astr[:(i+1)]
    return ''

#删除左右两边的空白
def rmsps(astr):
    return rrmsps(lrmsps(astr))



if __name__ == '__main__':
    hi = '    hello,world.      '
    print '删除左边空白:|%s|' % lrmsps(hi)
    print '删除右边空白:|%s|' % rrmsps(hi)
    print '删除两边空白:|%s|' % rmsps(hi)

 

2.运行代码,测试效果

[root@localhost python]# python rmspace.py
删除左边空白:|hello,world.      |
删除右边空白:|    hello,world.|
删除两边空白:|hello,world.|

 

 

*附录:使用list的方式模拟删除字符串左右两边的空白

代码如下:

#!/usr/bin/env python
#coding:utf8
"""
使用列表的方式删除左右两端的空白。
"""
from string import whitespace

def lrmsps(astr):
    result = list(astr)
    for i in xrange(len(result)):
        if result[0] not in whitespace:
            break
        result.pop(0)
    return ''.join(result)


def rrmsps(astr):
    result = list(astr)
    for i in xrange(len(result)):
        if result[-1] not in whitespace:
            break
        result.pop()
    return ''.join(result)

def rmsps(astr):
    return rrmsps(lrmsps(astr))


if __name__ == '__main__':
    hi = '     hello,world.    '
    print '|%s|' % lrmsps(hi)
    print '|%s|' % rrmsps(hi)
    print '|%s|' % rmsps(hi)

 

转载于:https://www.cnblogs.com/xkops/p/6244198.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值