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

python字符串 *** 作增、删、改、查、截取,第1张

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/786974.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存