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)
不是定义在类⾥⾯,为了简便就只是去除空⽩字符好了。⽽且如果中间连续出现了多空⽩字符,只会添加⼀个空格,伤脑筋。好吧,还是写⼀个正确的去除⾸尾空⽩字符的⽅式吧:
trim函数用于删除空格
def trim(s):
pat = repile("^\s*(.*?)\s*$")
rs = re.match(pat, s)
s = rs.group(1)
return s
注意那个?是⼀定需要的,否则会匹配到后⾯结尾处的空⽩字符的。