正则-Strip函数

来源:互联网 发布:linux tee 用法 编辑:程序博客网 时间:2024/06/16 15:30

正则-Strip函数

@(正则表达式)[正则,strip]

  • 正则-Strip函数
    • strip的正则表达式版本

strip()的正则表达式版本

写一个函数,它接受一个字符串,做的事情和strip()字符串方法一样。如果只传入了要去除的字符串,没有其他参数,那么就从该字符串首尾去除空白字符。否则,函数第二个参数指定的字符将从该字符串中去除。

import redef strip(text, chars=None):    """去除首尾的字符    :type text: string    :type chars: string    :rtype: string    """    if chars is None:        reg = re.compile('^ *| *$')    else:        reg = re.compile('^[' + chars + ']*|[' + chars + ']*$')    return reg.sub('', text)print(strip('   123456   '))  # 123456print(strip('   123456'))  # 123456print(strip('   123456'))  # 123456print(strip('123456   654321'))  # 123456   654321print(strip('123456   654321', '1'))  # 23456   65432print(strip('123456   654321', '1234'))  # 56   65print(strip('123456   654321', '124'))  # 3456   6543
0 0