zoukankan      html  css  js  c++  java
  • python文本 字符串开头或者结尾匹配

    python文本 字符串开头或者结尾匹配

    场景:

    字符串开头或者结尾匹配,一般是使用在匹配文件类型或者url

    一般使用startwith或者endwith


     
    >>> a='http://blog.csdn.net/raylee2007' 
     
    >>> a.startswith ('http'

      True 

    注意:这两个方法里面的参数可以是str,也可以是元组,但是不可以是列表和字典


     
    >>> a='http://blog.csdn.net/raylee2007' 
     
    >>> a.startswith (('http','ftp'
    )) 
      True 

    如果是列表或者字典,则报错

      >>> a='http://blog.csdn.net/raylee2007' 
     
    >>> a.startswith (['http','ftp'
    ]) 
      Traceback (most recent call last): 
        File
    "", line 1, in
      
          a.startswith ([
    'http','ftp'
    ]) 
     
    TypeError: startswith first arg must be str or a tuple of str, not
    list 
     
    >>>  

    其实,除了上面的方法, 也可以使用切片来实现,只不过代码看上去没那么好看而已


     
    >>> a='http://blog.csdn.net/raylee2007' 
     
    >>> a[0:4]=='http'
     
      True 
     
    >>>  

    当然,我们也可以用正则表达式来做,但是理解上面就稍微难度有点。

      >>> import re 
     
    >>> url = '
    http://www.python.org' 
     
    >>> re.match('http:|https:|ftp:'
    , url) 
     
    0, 5), match='http:'

     
    >>>
    help(re.match ) 
      Help on function match
    in module 
    re

       
      match(pattern, string, flags=
    0

          Try to apply the pattern at the start of the string, returning 
          a match object,
    or None if
    no match was found. 
       
     
    >>>  

  • 相关阅读:
    vim delete
    npm ERR! network connect ETIMEDOUT
    在 ubuntu 14.04 Unity 中清除和关闭 Totem 播放记录
    ubuntu 14.04 上 jvpn 使用说明
    LWP::Protocol::https not installed
    perl 安装模块
    触摸屏工作方式
    如何检测死锁并快速定位死锁位置
    如何用 yum 的一个包替换另一个包
    shell 中 here documemt << 与 <<- 的区别
  • 原文地址:https://www.cnblogs.com/quanweiru/p/8358895.html
Copyright © 2011-2022 走看看