在解析之前,如何为字符串变量“interface\u info”中的每一行剥离前缘空间?

2024-10-01 04:18:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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>

在上述代码的输出中,请注意列表中的每个字符串 前缘空间。我正试图在考试前把那些地方绊倒 字符串将出现在列表中。


Tags: retypeinterfaceapsplitaddrprintmhz
1条回答
网友
1楼 · 发布于 2024-10-01 04:18:16

使用lstrip只会删除phy#3之前的空白字符

您可以使用str.strip和map对split返回的所有项使用strip:

interface_split = map(str.strip, re.split(r'\n', ssid_extract.group(0)))

参见Python demo

如果只想删除左边的空白字符,另一种方法是首先从字符串中删除所有前导的空白字符,方法是使用^\s+re.sub并使用多行标志编译regex:

stripped = re.sub(re.compile('^\s+', re.MULTILINE), '', interface_info)

参见Python demo

相关问题 更多 >