Loading

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)

不是定义在类里面,为了简便就只是去除空白字符好了。而且如果中间连续出现了多空白字符,只会添加一个空格,伤脑筋。

好吧,还是写一个正确的去除首尾空白字符的方式吧:

def trim(s):
    pat = re.compile("^\s*(.*?)\s*$")
    rs = re.match(pat, s)
    s = rs.group(1)
    return s

注意那个?是一定需要的,否则会匹配到后面结尾处的空白字符的。

posted @ 2019-03-06 13:36  BasilGuo  阅读(6245)  评论(0编辑  收藏  举报