Formatizing the line.



  • There's a line of view:

    In [1]: p = '010203040506'
    

    Formulate:

    In [2]:"{0}:{1}:{2}:{3}:{4}:{5}".format(p[:2],p[2:4],p[4:6],p[6:8],p[8:10],p[10:12])
    

    I get the result:

    Out[3]: '01:02:03:04:05:06'
    

    Second option:

    ':'.join([p[x:x+2] for x in xrange(0, len(p), 2)])
    

    Any other options to simplify the layout?



  • import wrap from textwrap
    
    ':'.join(wrap(p, 2))
    

    There's so many ways you can think of:

    ':'.join(re.split('(\w{2})', p)[1::2])
    

    ':'.join('%02x' % ord(b) for b in binascii.unhexlify(p))

    '%02x:%02x:%02x:%02x:%02x:%02x' % struct.unpack('BBBBBB', binascii.unhexlify(p))

    ...


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2