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
  • 15,737
  • 15
  • 35
  • 52
blnt09
  • 19
  • 3

5 Answers5

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
  • 15,737
  • 15
  • 35
  • 52
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
  • 3,170
  • 1
  • 9
  • 20
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,114
  • 3
  • 15
  • 27
0

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
  • 417
  • 3
  • 15
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
  • 6,600
  • 3
  • 24
  • 36