import re
interface_info = '''
phy#3
Interface wlan1-cabin-2
ifindex 37
wdev 0x300000003
addr 06:53:1a:4e:07:02
ssid SSIDTEST3
type AP
channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz
Interface wlan1-cabin-1
ifindex 36
wdev 0x300000002
addr 06:53:1a:4e:07:01
ssid SSIDTEST2
type AP
channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz
Interface wlan1
ifindex 7
wdev 0x300000001
addr 06:53:1a:4e:07:00
ssid SSID1
type AP
channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz
phy#2
Interface wlan0
ifindex 6
wdev 0x200000001
addr 00:30:1a:4e:07:ac
type managed
'''
stripped = interface_info.lstrip(' \t\n\r')
ssid_regex = re.compile('Interface wlan1-cabin-2+((.*\n){6})')
ssid_extract = re.search(ssid_regex, stripped)
interface_split = re.split(r'\n', ssid_extract.group(0))
ssid = str(interface_split[4]).strip(' ssid ')
print(stripped)
print (ssid_extract)
print str(interface_split)
print (ssid)
输出:
<b>
<_sre.SRE_Match object at 0x7fb1665e2250>
['Interface wlan1-cabin-2', ' ifindex 37', ' wdev 0x300000003', ' addr 06:53:1a:4e:07:02', ' ssid SSIDTEST3', ' type AP', '']
SSIDTEST3`
</b>
在上述代码的输出中,请注意列表中的每个字符串 前缘空间。我正试图在考试前把那些地方绊倒 字符串将出现在列表中。
使用lstrip只会删除
phy#3
之前的空白字符您可以使用str.strip和map对split返回的所有项使用strip:
参见Python demo
如果只想删除左边的空白字符,另一种方法是首先从字符串中删除所有前导的空白字符,方法是使用
^\s+
和re.sub并使用多行标志编译regex:参见Python demo
相关问题 更多 >
编程相关推荐