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)

 

posted @ 2017-01-03 11:22  xkops  阅读(1575)  评论(0编辑  收藏  举报