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