python文本 字符串开头或者结尾匹配
2018-01-26 12:01
756 查看
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.
>>>
场景:
字符串开头或者结尾匹配,一般是使用在匹配文件类型或者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.
>>>
相关文章推荐
- 轻松python文本专题-字符串开头或者结尾匹配
- 轻松python文本专题-字符串开头或者结尾匹配
- 轻松python文本专题-字符串开头或者结尾匹配
- python 匹配字符串开头和结尾
- Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作
- 基于《PythonCookbook》的学习(2)——在字符串的卡头或结尾做文本匹配
- 对python 匹配字符串开头和结尾的方法详解
- Python: 字符串开头或结尾匹配str.startswith(),str.endswith()
- python 字符串开头或结尾匹配
- Python-字符串开头或结尾匹配
- Python: 去掉字符串开头、结尾或者中间不想要的字符
- Python: 字符串搜索和匹配,re.compile() 编译正则表达式字符串,然后使用match() , findall() 或者finditer() 等方法
- 正则表达式:检查一个句子或者字符串是否以大写字母开头,以句号结尾.
- python-12-如何判断字符串a是否以字符串b开头或结尾(改变文件权限)?
- python_如何判断字符串a以某个字符串开头或结尾?
- python根据开头和结尾字符串获取中间字符串的方法
- 字符串以什么开头或者结尾 前缀、后缀的判断
- iOS之字符串中是否以http开头或者以.com结尾
- 去掉字符串开头,结尾或者中间的空格及其他不想要的字符
- NSString字符串判断以某个str开头或者以某个str结尾