0

I want to put : after every second character:

def maccim():
    l = ["A", "B", "C", "D", "E", "F", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    macim = random.sample(l, 12)
    szo = ""
    for x in macim:
        szo += x
    print(szo)

maccim()

I want to get like this: 94:EA:60:F8:BC:2D as a mac address.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
blnt09
  • 13
  • 3

5 Answers5

1

The simplest way would be to use enumerate when you put together the string:

import random

def maccim():
    list=["A","B","C","D","E","F","0","1","2","3","4","5","6","7","8","9"]
    macim=random.sample(list,12)
    szo=""
    for index, x in enumerate(macim):
        szo+=x
        if (index+1)%2 == 0:
            szo+=":"
    szo = szo[:-1]
    print(szo)
maccim()

Then you can use the index to determine if you need to add an ':'

bluevulture
  • 422
  • 4
  • 16
1

Create couples of characters with slicing and then just join them with a ::

import random

def maccim():
    l = ["A","B","C","D","E","F","0","1","2","3","4","5","6","7","8","9"]
    macim = ''.join(random.sample(l, 12))

    print(':'.join(macim[i:i+2] for i in range(0, len(macim), 2)))
    
maccim()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

You can do it with brutal way

for i in range(len(macim)):
    szo += macin[i]
    if i % 2 and i < len(macim) - 1:
        szo += ":"

or fancy way

def chunks(l, n):
    n = max(1, n)
    return (l[i:i+n] for i in range(0, len(l), n))

...

":".join(chunks(macin, 2))
kosciej16
  • 6,294
  • 1
  • 18
  • 29
0

Here is another solution using list splice,

import random


def maccim():
    list_ = [
        "A", "B", "C", "D", "E", "F", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
    ]
    macim = random.sample(list_, 12)

    return ":".join([i + j for i, j in zip(macim[::2], macim[1::2])])


print(maccim())
sushanth
  • 8,275
  • 3
  • 17
  • 28
0

Just for fun, if you wanted a simple one-liner using zip and map:

import string
import random

chars = random.sample(string.hexdigits[:16], 12)

':'.join(map(''.join, zip(chars[::2], chars[1::2])))

This will output:

'07:9d:b5:1c:84:ae'
S3DEV
  • 8,768
  • 3
  • 31
  • 42