目標:
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 whitespacedef lrmsps(astr):result = list(astr)for i in xrange(len(result)):if result[0] not in whitespace:breakresult.pop(0)return ''.join(result)def rrmsps(astr):result = list(astr)for i in xrange(len(result)):if result[-1] not in whitespace:breakresult.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)
?