Python實現trim函數


Python中其實也有類似Java的trim函數的,叫做strip,舉例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
str = "0000000hello world0000000000"
print(str.strip( '0' ))  # 去除首尾字符 0
# hello world
 
str2 = "    hello world     "  # 去除首尾空格 print str2.strip()
# hello world

但是學了正則表達式就想自己來實現,好吧。Talk is cheap, show me the code.

def trim(s):
    r = re.findall('[\S]+', s)
    return " ".join(r)

不是定義在類里面,為了簡便就只是去除空白字符好了。而且如果中間連續出現了多空白字符,只會添加一個空格,傷腦筋。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM