轻松python文本专题-字符串开头或者结尾匹配
2015-08-27 21:58
836 查看
场景:
字符串开头或者结尾匹配,一般是使用在匹配文件类型或者url
一般使用startwith或者endwith
注意:这两个方法里面的参数可以是str,也可以是元组,但是不可以是列表和字典
如果是列表或者字典,则报错
其实,除了上面的方法, 也可以使用切片来实现,只不过代码看上去没那么好看而已
当然,我们也可以用正则表达式来做,但是理解上面就稍微难度有点。
就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学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 "<pyshell#1>", line 1, in <module> 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) <_sre.SRE_Match object; span=(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. >>>
就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录
相关文章推荐
- 轻松python文本专题-字符串开头或者结尾匹配
- Python中的sys.argv
- python itertools模块
- 拉格朗日插值python实现
- python学习笔记
- python学习笔记8
- Python 日志(logging)模块
- python if条件判断、for循环和while循环
- python爬虫爬取csdn博客专家所有博客内容
- 基于七牛Python SDK写的一个批量下载脚本
- QtCreator 3.x gdb python支持
- The Python Challenge 0~2
- 小甲鱼Python第十二讲课后题
- python 序列类型以及list(列表) 和 tuple(元组)详解 以及range的用法
- Python语法基础——关于全局变量与局部变量
- 几个Python科学计算发行版
- python copy and deeepcopy
- python---序列可使用的内建函数(BIFs)
- python 格式化
- 为Python添加默认模块搜索路径