当前位置 博文首页 > python strip()函数 介绍

    python strip()函数 介绍

    作者:admin 时间:2021-02-17 12:05

    描述
    Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。

    语法
    strip()方法语法:
    str.strip([chars]);

    参数
    chars -- 移除字符串头尾指定的字符。
    返回值
    返回移除字符串头尾指定的字符生成的新字符串。

    实例
    以下实例展示了strip()函数的使用方法:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    str = "0000000   jb51.net 0000000"
    print(str.strip( '0' )) # 去除首尾字符 0 
     
    str2 = "  jb51.net   "  # 去除首尾空格
    print(str2.strip())

    以上实例输出结果如下:

         jb51.net 
    jb51.net

    Python3 replace()方法

    描述
    replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

    语法
    replace()方法语法:

    str.replace(old, new[, max])
    参数
    old -- 将被替换的子字符串。
    new -- 新字符串,用于替换old子字符串。
    max -- 可选字符串, 替换不超过 max 次
    返回值
    返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

    实例
    以下实例展示了replace()函数的使用方法:

    #!/usr/bin/python3
     
    str = "欢迎访问站长博客www.jb51.net"
    print ("站长博客旧地址:", str)
    print ("站长博客新地址:", str.replace("jb51.net", "jbzj.com"))
     
    str = "this is string example....wow!!!"
    print (str.replace("is", "was", 3))

    以上实例输出结果如下:

    站长博客旧地址: www.jbzj.com
    站长博客新地址: www.jb51.net
    thwas was string example....wow!!!

    函数原型

    声明:s为字符串,rm为要删除的字符序列

    s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
    s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
    s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符

    注意:

    1. 当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')

    例如:

    >>> a = '   123'
    >>> a.strip()
    '123'
    >>> a='\t\tabc'
    'abc'
    >>> a = 'sdff\r\n'
    >>> a.strip()
    'sdff'

    2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。

    例如 :

    >>> a = '123abc'
    >>> a.strip('21')
    '3abc'  结果是一样的
    >>> a.strip('12')
    '3abc'

    文章就到这了,需要的朋友可以参考一下

    js