中国最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2

python教程

  • Python 入门教程
  • Python 基础教程

    Python 高级教程

    Python 常用资源

    Python 拓展阅读

    4. python 修改字符串实例总结

    阅读 (2144)

    4. python 修改字符串实例总结

    我们知道python里面字符串是不可原处直接修改的,为了是原来的字符串修改过来,我们有一下方法:

    1.分片和合并

      >>> a='abcde'  
      >>> b='fghij'  
      >>> c=a[1:3]+b[2:5]+' end'  
      >>> c  
      'bchij end'  
      >>>   

    2.replace()

      >>> a='aaabbbcccddd'  
      >>> a.replace ('aaa','xxx')  
      'xxxbbbcccddd'  
      >>>   

    3.结合find()和分片

    
      >>> a='aaaxbbbcccxddd'  
      >>> where = a.find ('x')  
      >>> where  
      3  
      >>> a[:where]+'ttttt'+a[where:]  
      'aaatttttxbbbcccxddd'  
      >>>   

    上面的三种方法,虽然都修改了源字符串,其实它们没有直接在原处修改,只是重新创建一个新的字符串对象

    4.使用可修改的列表

    可能你需要修改超长文本多个地方,这时候上面的方法性能不好,所以需要转换为可以修改的对象-列表

      >>> a='aaaxbbbcccxddd'  
      >>> b=list(a)  
      >>> b  
      ['a''a''a''x''b''b''b''c''c''c''x''d''d''d']  
      >>> b[2]='x'  
      >>> b[7]='x'  
      >>> b  
      ['a''a''x''x''b''b''b''x''c''c''x''d''d''d']  
      >>> a=''.join (b)  
      >>> a  
      'aaxxbbbxccxddd'  
      >>>   


    关闭
    程序员人生