栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python字符串操作增、删、改、查、截取

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python字符串操作增、删、改、查、截取

python常用的字符串操作
  • 记录python中字符串的操作,以后有了其他的操作会在这个文件中追加
目录
  1. 主函数
  2. 字符串相加
  3. N个字符串相加
  4. 字符串替换
  5. 循环读取字符串
  6. 字符串截取
  7. 字符串查找
  • 以下所以函数调用的main函数,结果都是基于主函数中的字符串得出的

      if __name__ == "__main__":
          str1 = "Yuang"
          str2 = "PangZi"
          str3 = "YuangPangZi"
          str_list = [str1, str2, str3]
          StrAdd(str1, str2)
          StrSub(str3, str1)
          StrAddList(str_list)
          LoopRead(str1)
          StrSplit(str3)
          FindStr(str3, str1)
          FindStr2(str3, str1)
    
  • 字符串相加

    def StrAdd(str1:str, str2:str):  #指定参数的数据类型
        res = str1 + str2
        print("StrAdd: ",res)
        return res
    
    StrAdd:  YuangPangZi
    
  • N个字符串相加

    def StrAddList(*args):
    res = ""
    for s in args[0]:
        if isinstance(s, str):
            res += s
    print("StrAddList: ", res)
    return res
    
    StrAddList:  YuangPangZiYuangPangZi
    
  • 字符串替换

    def StrSub(source:str, str1:str): 
        res = source.replace(str1, "") #说是减法实则替换
        print("StrSub: ", res)
        return res
    
    StrSub:  PangZi
    
  • 循环读取字符串

    def LoopRead(source:str):
        for i in source:
            print("Loop Str: ", i)
    
    Loop Str:  Y
    Loop Str:  u
    Loop Str:  a
    Loop Str:  n
    Loop Str:  g
    
  • 字符串截取

    def StrSplit(source:str):
        print("get one char:", source[0], source[1]) #取字符串指定内容1:
        print("get sting in range:",  source[0:2]) #左闭右开 取字符串的指定范围
        print("get char in range for behand:", source[-3: -1]) #从后往前数截取
        print("get one char:", source[-1], source[-2])
    
    get one char: Y u
    get sting in range: Yu
    get char in range for behand: gZ
    get one char: i Z
    
  • 字符串查找

    #在source中查找tag是否存在
    def FindStr(source:str, tag:str):
        if tag in source:
            print("True")
            return True
        else:
            print("False")
            return False
    
    True
    
    import re
    #在source中查找tag并获取数量
    def FindStr2(source:str, tag:str):
        res = re.findall(tag, source)
        print("res:", res)
        print("res len", len(res))
    
    res: ['Yuang']
    res len 1
    

s = re.findall(tag, source)
print(“res:”, res)
print(“res len”, len(res))

```shell
res: ['Yuang']
res len 1
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/840484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号