• 常用的字符串内建函数(一)


    1、capitalize()方法

    将字符串的首字母转换为大写,其他字母为小写 ,首字符如果是非字母,首字母不会转换成大写,会转换成小写

    用法str.capitalize()

    2、swapcase()方法

    将大写字母转换为小写字母,将小写字母转换为大写字母

    用法:str.swapcase()

    str1 = "Study"
    str2 = "study"
    str3 = "sTUDY"
    str4 = "123Study"
    print(str1.swapcase())
    print(str2.swapcase())
    print(str3.swapcase())
    print(str4.swapcase())

     3、replace()方法

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

    语法:replace(old, new[, max])

    • old -- 将被替换的子字符串。
    • new -- 新字符串,用于替换old子字符串。
    • max -- 可选字符串, 替换不超过 max 次

    str5 = "There is example,There is example,There is example,There is example"

    print(str5.replace("is", "was", 3))

    4、find()方法与rfind()方法

    从左至右查找字符串中是否包含子字符串,如果指定开始(beg)和结束(end)范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。

    语法:str.find(str, beg=0, end=len(string))

    str -- 指定检索的字符串

    beg--开始索引位置,默认为0

    end--结束索引,默认为字符串的长度

    str5 = "There is example,There is example,There is example,There is example"
    str6 = "is"
    print(str5.find(str6, 0, 5))
    print(str5.find(str6, 5))
    print(str5.find(str6, 10))

     rfind()方法 :与find()方法类似,返回字符串最后一次出现的位置,如果没有匹配项则返回-1。 rfind()方法是从右侧开始查找

    5、count()方法

    用于统计字符串中某字符出现的次数,可选参数为字符串搜索的开始位置和结束位置

    返回值:该方法返回子字符串在字符串中出现的次数

    语法:str.count(sub,start =0 ,end = len(string))

    sub:搜索的子字符串

    start:字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。

    end:字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置

    str5 = "There is example,There is example,There is example,There is example"
    sub = "is"
    print(str5.count(sub))
    print(str5.count(sub, 0, 5,))

    不忘初心,坚持下去
  • 相关阅读:
    Symmetric Order
    Red and Black
    Sticks(递归经典)
    Pascal Library
    cantor的数表
    OJ 调试技巧:VS2010 中 通过设置编译参数定义宏,无需修改源文件重定向标准输入输出
    strcmp
    最短周期串
    字母重排
    codeblocks 单步调试
  • 原文地址:https://www.cnblogs.com/keepkeep/p/11570460.html
Copyright © 2020-2023  润新知