为什么我们有连字符是在mac地址的字符串前面



我正在尝试获取存储在mssql中的mac地址列表。下面是我得到的输出。由于现有表行中有空行,我们将获得"无">

[('BC5369778427',(,('=',(,[104B7DE14D95',],[无,],('00505D915F99],(,]

我想在下面的格式中只过滤这个输出的mac地址

我想要的输出应该是BC-53-69-77-84-27 10-4B-7D-E1-4D-95 00-50-5D-91-5F-99

我尝试了以下python代码:

cur1 = conn.cursor()
cur2 = t2.cursor()
cur2.execute("CREATE TABLE macauth9 (macaddress TEXT);") // creates the new table to insert after filtering
t2.commit()
mac = cur1.execute("select MACAddress from myorginal-table").fetchall() //fetches all the mac address from mssql
stringmac = str(mac)
stringmac = stringmac.replace("(", "")
stringmac = stringmac.replace(")", "")
stringmac = stringmac.replace("'", "")
stringmac = stringmac.replace("'", "")
stringmac = stringmac.replace(",", "")
stringmac = stringmac.replace("[None", "")
stringmac = stringmac.replace("]", "")
stringmac = stringmac.replace("=", "")
stringmac = stringmac.replace("r", "")

dil = '-'.join(stringmac[i:i+2] for i in range(0,len(stringmac),2))
mag = repr(str(dil))
cur2.execute("INSERT INTO macauth9(macaddress) VALUES(%s);", (mag,))
t2.commit()
conn.close() # getting -BC-53-69-77-84-27-   -  -  -  -10-4B-7D-E1-4D-95-  -00-50-5D-91-5F-99-
t2.close() # output should be   BC-53-69-77-84-27 10-4B-7D-E1-4D-95  00-50-5D-91-5F-99

在上面的代码之后,我得到了这个:


'-BC-53-69-77-84-27------10-4B-7D-E1-4D-95----00-50-5D-91-5F-99-

我只想删除mac地址前面的连字符和行为空的连字符(---(:预期结果应该是BC-53-69-77-84-27 10-4B-7D-E1-4D-95 00-50-5D-91-5F-99

您的SQL查询生成了一个元组列表,但您将其转换为字符串表示,然后试图对其进行操作,这是错误的做法。相反,您可以迭代列表,忽略显然不是MAC地址的值,并处理那些是MAC地址的。

示例代码:

import re
output = [ ('BC5369778427', ), ('=', ),('104B7DE14D95', ),
(None, ), ('00505D915F99', ), (None, ),]
for value in output:
value = value[0] # extract from the tuple
if value is None or len(value) < 2:
continue # skip useless values
# Use regular expressions to put a '-' after every 2 characters:
mac_rep = re.sub(r'[^-]{2}', r'g<0>-', value)
mac_rep = mac_rep[:-1] # the above also puts '-' at the end, so remove it
print(mac_rep)

我使用了正则表达式,但您使用联接的方法也同样有效。

如果你是一个不关心可读性的懒惰堕落者,你也可以在一行中创建一个格式化的MAC列表:

[re.sub(r'[^-]{2}',r'g<0>-',v)[:-1] for (v,) in output if v is not None and len(v) > 2]

最新更新