问题
经常遇到匹配字符串,比如查看文件权限,通信端口矩阵,网页中是否包含文本内容
方法
Python匹配字符串有三个方法:find,startswith,endwith
- find:查看log中IP地址
ifconfig_str = '''
eth0 Link encap:Ethernet HWaddr 00:1C:42:20:ED:B5
inet addr:10.211.55.9 Bcast:10.211.55.255 Mask:255.255.255.0
inet6 addr: fdb2:2c26:f4e4:0:972:417e:7886:6d63/64 Scope:Global
inet6 addr: fdb2:2c26:f4e4:0:21c:42ff:fe20:edb5/64 Scope:Global
inet6 addr: fe80::21c:42ff:fe20:edb5/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:19303 errors:0 dropped:0 overruns:0 frame:0
TX packets:10650 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:27642042 (26.3 Mb) TX bytes:677015 (661.1 Kb)
'''
pos = ifconfig_str.find('10.211.55.9')
if pos == -1:
print("not find")
else:
print("find")
- startswith
startswith函数就表示字符串是什么开头的,返回True or False。比如:
test = 'hello word'
print( test.startswith('hello') )
print( test.startswith('world'))
- endswith
endswith函数和startswith函数刚好相反,是表示字符串以什么内容结束