[TOC] >[success] # 开头startswith 结尾endswith ~~~ line = "asdf fjdk; afed,asdf, foo" a = line.endswith("foo") print(a) 打印结果: True ~~~ >[danger] ##### 一组数据时候用元组 ~~~ line = "asdf fjdk; afed,asdf, foo" a = line.endswith(("foo","ss")) print(a) 打印结果: True ~~~ >[success] # 任意位置匹配 >[danger] ##### str.find ~~~ line = "asdf fjdk; afed,asdf, foo" a = line.find("foo") print(a) 打印结果: 25 ~~~ >[info] ## 正则 ~~~ re.search() 在一个字符串中搜索匹配正则表达的第一个位置,返回match对象 re.match() 从一个字符串的开始位置起匹配正则表达式,返回match re.findall() 搜索字符串,以列表类型返回全部能匹配字符串 re.finditer() 搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象 group 分组的形式可以取出匹配的值 ~~~ >[danger] ##### 预编译re.compile ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.compile(r'foo') print(a.search(line)) 打印结果: <_sre.SRE_Match object; span=(25, 28), match='foo'> ~~~ >[danger] ##### 只匹配到第一个 -- re.search ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.search("foo",line) print(a) 打印结果: <_sre.SRE_Match object; span=(25, 28), match='foo'> ~~~ >[danger] ##### 只从头匹配 -- re.match ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.match("foo",line) print(a) 打印结果: None ~~~ ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.match("asdf",line) print(a) 打印结果: <_sre.SRE_Match object; span=(0, 4), match='asdf'> ~~~ >[danger] ##### 匹配所有--re.findall ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.findall("foo",line) print(a) 打印结果: ['foo', 'foo'] ~~~ >[danger] ##### 分组才能迭代-- finditer ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.finditer('(foo)',line) for i in a: print(i.groups()) 打印结果: ('foo',) ('foo',) ~~~