Python 字符串学习

字符串处理

  1,字符串分割
      (a)split 方法

        str1 = "http:// www.qwe, qwe; qwe,qwe"
        import re
        re.split(r'[,;\s]\s*',str1)
        
   >>> ['http://', 'www.qwe', 'qwe', 'qwe', 'qwe']

     一般简单的可以使用 str.split("xxx")进行分割。但是re.split( ) 用起来更加的灵活。


  2, 字符串开头和结尾

        (a) str.startswith( )/str.endswith( )

      filename = "http://zaixiankefu.txt"
      filename.endswith(".txt")
      
   >>>True
   
      filename.startswith("http:")
   >>>True
   
      # startswith( )和 endswith( )可以接收一个元组数据,注意是元组。
   
      choice = (".txt",".avi")
      filename.endswith(choice)
   >>>True

        (b) 也可以使用切片来判断

      if filename[:4] == "http" and filename[-4:] == ".txt":
          return True

   

    3,字符串匹配

            简单的就是str.startswith( ),str.endswith( ),str.find(),前两种返回时bool 值,find是返回第一次匹配的下标值。

            使用正则进行匹配(更多方法参考正则文档)。

       (a)re.match( )

               match 总是从字符串开始去匹配 。如匹配则返回一个匹配对象,失败返回None。

       str1 = "2018/12/20"
       import re
       re.match(r'\d*/',str1)
   >>> <_sre.SRE_Match object; span=(0, 5), match='2018/'>

         (b) re.search( )

               search 会匹配整个字符串。如匹配则返回一个匹配对象,失败返回None。

      re.search(r'/\d*/',str1)
   >>>  <_sre.SRE_Match object; span=(4, 8), match='/12/'>

        (c) re.findall( )

               findall( )会匹配整个字符串,匹配则返回一个list列表,要么有值要么空

                如果返回的值过多,可以使用 finditer( )来替代。

      str1 = "www.baidu.com"
      import re
      re.finditer(r'w',str1) #会返回一个可迭代对象
  >>> <callable_iterator at 0x5be230>

     4,字符串替换

          简单的替换可以使用 str.replace(old,new) 进行操作。

          re.sub( )可以更加灵活处理。




 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章