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