python字符串匹配开头_Python字符串开头或末尾匹配

当你需要通过指定的文本模式去检查字符串的开头或者结尾的时候,比如文件名后缀,URL Scheme等等。

检查字符串开头或结尾的一个简单方法是使用str.startswith()或者是str.endswith()方法, 案例如下: >>> pyfile = 'printf.py'

>>> pyfile.endswith('.py')

True

>>> pyfile.startswith('printf.')

True

>>> down_url = 'https://fashengba.com'

>>> down_url.startswith('https://')

True

从之前的文章Python数据类型之字符串中介绍startswitch和endswitch的源码中可知这两方法是是支持tuple类型的,所以如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去, 然后传给startswith()或者endswith()方法中即可,案例如下: >>> import os

>>> file_names = os.listdir('.')

>>> file_names

['.DS_Store', 'view.txt', 'sshlogin.sh', 'domain_search.py', 'scheduling.php']

>>> [ name for name in file_names if name.endswith(('.sh', '.py', '.php')) ]

['sshlogin.sh', 'domain_search.py', 'scheduling.php']

>>> any((name.endswith('py') for name in file_names))

True any(iterable)说明:参数iterable, 可迭代对象;如果当iterable所有的值都是0、''或False时,那么结果为False,如果所有元素中有一个值非0、''或False,那么结果就为True

如上可知如果需要利用startswith()或者endswith()方法,这个方法中必须要输入一个元组作为参数。 如果你恰巧有一个list或者set类型的选择项, 要确保传递参数前先调用tuple()将其转换为元组类型, 才能正常运行,示例如下: >>> suffix = ['http:', 'https:', 'ftp:']

>>> url = 'https://fashengba.com'

>>> url.startswith(suffix)

Traceback (most recent call last):

File "", line 1, in

url.startswith(suffix)

TypeError: startswith first arg must be str or a tuple of str, not list

>>> url.startswith(tuple(suffix))

True

startswith() 和 endswith() 方法提供了一个非常方便的方式去做字符串开头和结尾的检查。 类似的操作也可以使用切片来实现,虽然代码看起来没有那么优雅, 示例如下: >>> file_name = 'hello.py'

>>> file_name[-3:] == '.py'

True

>>> blog_url = 'https://fashengba.com'

>>> blog_url[:5] == 'http:' or blog_url[:6] == 'https:' or blog_url[:4] == 'ftp:'

True

当然你还可以使用正则表达式去实现,比如: >>> import re

>>> blog_url = 'https://fashengba.com'

>>> re.match('http:|https:|ftp:', blog_url)

>>>

>>> print('match success') if re.match('http:|https:|ftp:', blog_url) else print('match failed')

match success

这种方式也行得通,但是对于这种简单的匹配实在是有点小材大用了,so,用startswith()或者endswith()方法更加简单并且运行会更快些。

最后提一下,当和其他操作比如普通数据聚合相结合的时候 startswith() 和 endswith() 方法是很不错的。 比如,下面这个语句检查某个文件夹中是否存在指定的文件类型: >>> from os import listdir

>>> if any(name.endswith(('.txt', '.sh')) for name in listdir('.')):

... print('ok')

...

...

ok

本文由 空心菜 创作,采用 知识共享署名4.0 国际许可协议进行许可

本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名

最后编辑时间为: Jun 20, 2018 at 04:19 pm

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值