每隔第n个字符拆分字符串并附加':'

时间:2017-12-29 15:40:03

标签: python loops mac-address

我已将某些交换机MAC地址表读入文件,并且出于某种原因,如果格式化为MAC地址,则将其写入:

' aabb.eeff.hhii'

这不是MAC地址应该是什么,它应该遵循:' aa:bb:cc:dd:ee:ff'

我在撰写本文时已经看过评分最高的建议,并找到了一个可能符合我需求但却无法运作的答案

satomacoto's answer

MAC在一个列表中,所以当我运行循环时,我可以看到它们全部:

当前输出

['8424.aa21.4er9','fa2']
['94f1.3002.c43a','fa1']

我只想追加':'在第2个第n个角色,我可以删除'。'通过简单的替换,所以不要担心

所需的输出

['84:24:aa:21:4e:r9','fa2']
['94:f1:30:02:c4:3a','fa1']

我的代码

info = []
newinfo = []
file = open('switchoutput')
newfile = file.read().split('switch')
macaddtable = newfile[3].split('\\r')
for x in macaddtable:
   if '\\n' in x:
       x = x.replace('\\n', '')
   if carriage in x:
       x = x.replace(carriage, '')
   if '_#' in x:
       x = x.replace('_#', '')
   x.split('/r')
   info.append(x)
for x in info:
   if "Dynamic" in x:
      x = x.replace('Dynamic', '')
   if 'SVL' in x:
      x = x.replace('SVL', '')
   newinfo.append(x.split(' '))
for x in newinfo:
   for x in x[:1]:
       if '.' in x:
           x = x.replace('.', '')
   print(x)

5 个答案:

答案 0 :(得分:2)

借用you linked的解决方案,您可以按如下方式实现:

macs = [['8424.aa21.4er9','fa2'], ['94f1.3002.c43a','fa1']]

macs_fixed = [(":".join(map(''.join, zip(*[iter(m[0].replace(".", ""))]*2))), m[1]) for m in macs]

哪个收益率:

[('84:24:aa:21:4e:r9', 'fa2'), ('94:f1:30:02:c4:3a', 'fa1')]

答案 1 :(得分:2)

如果你喜欢正则表达式:

re.sub

模板字符串查找两个任意字符'(..)'并将它们分配给组1.然后允许0或1个点跟随'\。?'并确保在最后没有匹配'(?!$)'。然后将每个匹配替换为其组1加冒号。

这使用{{1}}对非重叠匹配进行操作的事实。

答案 2 :(得分:1)

x = '8424.aa21.4er9'.replace('.','')
print(':'.join(x[y:y+2] for y in range(0, len(x) - 1, 2)))
>> 84:24:aa:21:4e:r9

一旦你清理完字符串就迭代它,每次循环字符串时抓住2个字符串。使用range()第三个可选参数,您可以遍历每个第二个元素。使用join()在您正在迭代的两个元素之间添加:

答案 3 :(得分:1)

您可以使用re模块来实现所需的输出。

import re

s = '8424.aa21.4er9'
s = s.replace('.','')
groups = re.findall(r'([a-zA-Z0-9]{2})', s)
mac = ":".join(groups)
#'84:24:aa:21:4e:r9'

正则表达式解释

  • [a-zA-Z0-9]:匹配任何字母或数字
  • {2}:最多匹配2个字符。

通过这种方式,您可以获得两个人的组,然后在:加入他们以获得所需的mac地址格式

答案 4 :(得分:0)

wrong_mac = '8424.aa21.4er9'
correct_mac = ''.join(wrong_mac.split('.'))

correct_mac  = ':'.join(correct_mac[i:i+2] for i in range(0, len(correct_mac), 2))

print(correct_mac)
相关问题