• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

对python 匹配字符串开头和结尾的方法详解

python 搞代码 4年前 (2022-01-07) 32次浏览 已收录 0个评论

今天小编就为大家分享一篇对python 匹配字符串开头和结尾的方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1、你需要通过指定的文本模式去检查字符串的开头或者结尾,比如文件名后缀,URL Scheme 等等。检 查 字 符 串 开 头 或 结 尾 的 一 个 简 单 方 法 是 使 用str.startswith() 或 者 是str.endswith()方法。比如:

 >>> filename = 'spam.txt' >>> filename.endswith('.txt') True >>> filename.startswith('file:') False >>> url = 'http://www.python.org' >>> url.startswith('http:') True >>> 

2、如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去,然后传给 startswith()或者 endswith() 方法:

 >>> import os >>> filenames = os.listdir('.') >>> filenames [ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ] >>> [name for name in filenames if name.endswith(('.c', '.h')) ] ['foo.c', 'spam.c', 'spam.h' >>> any(name.endswith('.py') for name in filenames) True >>> #示例2 from urllib.request import urlopen def read_data(name): if name.startswith(('http:', 'https:', 'ftp:')): return urlopen(name).read() else: with open(name) as f: return f.read() 

奇怪的是,这个方法中必须要输入一个元组作为参数。如果你恰巧有一个list 或者 set类型的选择项,要确保传递参数前先调用 tuple()将其转换为元组类型。比如:

 >>> choices = ['http:', 'ftp:'] >>> url = 'http://www.python.org' >>> url.startswith(choices) Traceback (most recent call last): File "", line 1, in  TypeError: startswith first arg must be str or a tuple of str, not list >>> url.startswith(tuple(c<div style="color:transparent">来源gaodai.ma#com搞##代!^码网</div>hoices)) True >>>

3、startswith() 和 endswith() 方法提供了一个非常方便的方式去做字符串开头和结尾的检查。类似的操作也可以使用切片来实现,但是代码看起来没有那么优雅。比如:

 >>> filename = 'spam.txt' >>> filename[-4:] == '.txt' True >>> url = 'http://www.python.org' >>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:' True >>>

4、你可以能还想使用正则表达式去实现,比如:

 >>> import re >>> url = 'http://www.python.org' >>> re.match('http:jhttps:jftp:', url)  >>>

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

 if any(name.endswith(('.c', '.h')) for name in listdir(dirname)): ...

以上这篇对python 匹配字符串开头和结尾的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持gaodaima搞代码网

以上就是对python 匹配字符串开头和结尾的方法详解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:对python 匹配字符串开头和结尾的方法详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址