• python之字符串【str】


    我们用下面这个字符串来做测试

    testStr = "ZhanSan"
    

    1、__cantains__

    # 判断字符串是否包含某个子串,包含则返回true,不包含则返回false
    print(testStr.__contains__("a"))
    print(testStr.__contains__("x"))
    

    2、capitailize

    # 字符串的首字符大写
    print(testStr.capitalize())
    

    3、center,ljust,rjust

    # 填充字符串,把字符串放在中间
    print(testStr.center(10,"_"))
    
    # 填充字符串,把字符串放在左边
    print(testStr.ljust(14,"_"))
    # ZhanSan_______
    
    # 填充字符串,把字符串放在右边
    print(testStr.rjust(14,"_"))
    # _______ZhanSan
    

    4、count

    # 统计子串在字符串中出现的次数
    print(testStr.count("a"))
    

    5、endwith,startwith

    # 判断字符串是否已某个子串结尾
    print(testStr.endswith("z"))
    
    # 判断字符串是否已某个子串开头
    print(testStr.startswith("z"))
    

    6、find

    # 在字符串中查找某个字符串,只返回第一个查到的字符串,存在返回子串的索引,不存在返回-1
    print(testStr.find("a"))
    
    print(testStr.find("X"))
    

    7、index

    # 返回子串在字符串中的索引,存在返回索引,不存在则报错
    print(testStr.index("a"))
    
    print(testStr.index("X"))
    

    8、join

    # 使用指定字符连接字符串
    print("_".join(testStr))
    # Z_h_a_n_S_a_n
    

    9、lower、upper

    # 转换字符串为小写
    print(testStr.lower())
    # zhansan
    
    # 转换字符串为大写
    print(testStr.upper())
    # ZHANSAN
    

    10、strip、lstrip、rstrip

    # 在字符串左边去掉指定的子串
    print(testStr.lstrip("Z"))
    # hanSan
    
    # 在字符串右边去掉指定子串
    print(testStr.rstrip("n"))
    # ZhanSa
    
    # 在字符串两边去掉指定子串
    print(testStr.strip("x"))
    

    11、partition

    # 按照指定的子串分割字符串
    print(testStr.partition("a"))
    # ('Zh', 'a', 'nSan')
    

    12、replace

    # 替换字符串
    print(testStr.replace("a","T",1))
    # ZhTnSan
    
    print(testStr.replace("a","T",2))
    # ZhTnSTn
    

    13、split

    # 分割字符串
    print(testStr.split("a"))
    # ['Zh', 'nS', 'n']
    

    14、swapcase

    # 大小写互换
    print(testStr.swapcase())
    # zHANsAN
    

    15、tiile

    temp = "zhan ni hao"
    
    print(temp.title())
    # Zhan Ni Hao
    
  • 相关阅读:
    黄聪:VirtualBox 安装ghost版windows XP
    黄聪:Delphi 关键字详解[整理于 "橙子" 的帖子]
    黄聪:全局变量 HInstance 到底是在什么时候赋值的?
    黄聪:演示 Rect、Bounds 生成 TRect 的区别
    黄聪:C#操作合并多个Word文档
    黄聪:C# .Net三层架构[转]
    黄聪:遗传算法实现自动组卷、随机抽题
    黄聪:SQL转换日期字段的问题——SQL中CONVERT转化函数的用法[转]
    黄聪:System 提供的编译期函数
    黄聪:语言字符集
  • 原文地址:https://www.cnblogs.com/bainianminguo/p/6408026.html
Copyright © 2020-2023  润新知