Python模拟删除字符串两边的空白
生活随笔
收集整理的這篇文章主要介紹了
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 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)?
轉載于:https://www.cnblogs.com/xkops/p/6244198.html
總結
以上是生活随笔為你收集整理的Python模拟删除字符串两边的空白的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: split注意事项
- 下一篇: python 自动化之路 day 08_