zoukankan      html  css  js  c++  java
  • Python学习-字符串函数操作1

    字符串的函数操作

    capitalize():可以将字符串首字母变为大写

    返回值:首字符大写后的新字符串

    str = "liu"
    print(str.capitalize());   // Liu
    print(str);        //  liu

    casefold():作用于lower() 相同,不同点是比它的功能更全面,可以将一些未知的变为小写

    返回值:全部变为小写后的新字符串

    str = "LIU"
    print(str.casefold());   // liu
    print(str);        //   LIU
    

    center(width,fillchar=None):根据指定的字符串(1个),将原来的字符串填充到指定长度

    width:设置输出的字符串总长度

    fillchar:对空白部分进行填充,必须是一个字符(可有可无,但是只可以有一个)

    注意点:只有当字符串长度小于目标结果字符串的长度 ----->才会填充

    str = 'liu'
    m = str.center(10,'*');
    print(m);        //  ***liu**** 

    count(sub,start=None,end=None):计算要查找字符串的出现次数

    sub:需要查找的字符串

    start=None:开始查找的起始位置,默认起始的位置为可以省略(0)

    end=None:结束查找的位置,可以省略,默认为字符串的总长度len(str)

    str = 'liwuvjdfjuidjio'
    m = str.count('j');
    n = str.count('j',6)
    print(m);    //3
    print(n);    //2
    

    startswith(prefix,start,end):查找是否以指定字符串开头

    endswith(suffix,start=None,end=None):查找是否以指定字符串结尾

    prefix:需要查找的字符串子序列

    start:开始查找的起始位置,默认起始的位置为可以省略(0)

    end:结束查找的位置,可以省略,默认为字符串的总长度len(str)

    str = 'liuwen'
    m = str.startswith('li')
    n = str.endswith('li',2);
    print(m);  //True  
    print(n);    //False
    

    lower():可以将一个字符串中的所有字母变为小写

    upper():可以将一个字符串中的所有字母变为小写

    注意:他们都不会修改原字符串本身

    str1 = 'Wo Shi Liu Wen';
    print(str1.lower());  // wo shi liu wen
    print(str1.upper());  // WO SHI LIU WEN
    

    replace(old,new[,count]):使用给定的新字符串,替换原来字符串中的旧字符串,不会修改原字符串

    old:旧字符串

    new:要替换的新字符串

    count:要替换的个数

    str = 'liuweniumingiumm';
    res1 = str.replace('iu','aa');
    res2 = str.replace('iu','aa',2);
    print(res1);     // laawenaamingaamm
    print(res2);     // laawenaamingiumm
    

      

  • 相关阅读:
    [LeetCode] Output Contest Matches 输出比赛匹配对
    [LeetCode] 527. Word Abbreviation 单词缩写
    [LeetCode] Permutation in String 字符串中的全排列
    [LeetCode] 560. Subarray Sum Equals K 子数组和为K
    [LeetCode] Reshape the Matrix 重塑矩阵
    [LeetCode] 536. Construct Binary Tree from String 从字符串创建二叉树
    [LeetCode] IPO 上市
    [LeetCode] Binary Tree Tilt 二叉树的坡度
    [LeetCode] Array Partition I 数组分割之一
    [LeetCode] Zuma Game 祖玛游戏
  • 原文地址:https://www.cnblogs.com/pcliu/p/9824420.html
Copyright © 2011-2022 走看看