代码之家  ›  专栏  ›  技术社区  ›  Ganesh Thampi

python中的随机mac地址生成器

  •  1
  • Ganesh Thampi  · 技术社区  · 6 年前

    我对python相当陌生,在寻找生成随机MAC地址的解决方案时发现:

    ':'.join('%02x'%random.randint(0,255) for x in range(6))
    

    我想了解的是 '%02x'% 在代码中。它与mac地址的表示方式有关吗?mac地址是一个48位的十六进制值,由 : ?

    2 回复  |  直到 6 年前
        1
  •  2
  •   fferri    6 年前

    https://docs.python.org/2/library/stdtypes.html#string-formatting

    '%02x' 是用于指定零填充的两位数十六进制数的格式字符串。

    '%02x' % number 将使用此格式的数字创建实际字符串。

        2
  •  1
  •   BoarGules    6 年前

    如果你不理解一个列表的理解,那么最好的策略就是把它解开。

    myhexdigits = []
    for x in range(6):
        # x will be set to the values 0 to 5
        a = random.randint(0,255)
        # a will be some 8-bit quantity
        hex = '%02x' % a
        # hex will be 2 hexadecimal digits with a leading 0 if necessary
        # you need 2 hexadecimal digits to represent 8 bits
        myhexdigits.append(hex)
        # save for after the loop ends
    print (':'.join(myhexdigits))
    # using : as the delimiter, join the 2-digit hex strings together into
    # a single string