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)

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

原文地址:https://www.cnblogs.com/basilguo/p/python_regex_trim.html