[Python] Inserting a sign after every n-th character

Hello All,

I am writing a script to convert MAC addresses. I want to be able to convert "23edfd56ab90" to "23:ed:fd:56:ab:90". Is there a function in python I can use to do that? That is, inserting a ':' after every second character in a string?

Thanks for your time and help,
atwinix
 
I would suspect regexp search-and-replace could help.
Otherwise split the string into pieces of two, and then do
Code:
for(length(array)){ cat(string,':')
 
There is no standard function to do that, but it's easy enough to add:

Code:
string = "23edfd56ab90"
print ':'.join([string[i:i+2] for i in range(0, len(string), 2)])
 
Alt said:
Code:
string = "23edfd56ab90"
re.sub(r'(.{2})(?!$)', r'\1:', string)

This is bad. Regular expressions should be avoided when simple algorithm can be used, they are waste of resources.
 
"Bad" is relative. The simple algorithms here aren't all that simple. dh's in post #3 seems to be the canonical way. Likely faster, but depends on how many addresses are being processed. Alt's regex version is shorter but the quantifiers kind of obscure the meaning; how about:
Code:
re.sub(r'(..)', r'\1:', string, 5)
 
expl said:
This is bad. Regular expressions should be avoided when simple algorithm can be used, they are waste of resources.
He is "writing a script to convert MAC addresses"
 
hi,
i want to do the same but i have problem with space for example
'23edfd56ab90' to '23:ed:fd:56:ab:90:'
'23 ed f d5 6a b9 0 ' to ' 23: ed: f: d5: 6a: b9: 0: '
any help for this?
 
def lor(sentence) :


a = sentence.replace("\n","").replace("\r","")
b = a
i = 0
while ( i < len(a) ) :
b = b[:2+ 2*i ] + ':' + b[ 2+ 2*i :]
i = i + 2
return b

my problem is when i have space
'abcdef g abs' i want 'ab:cd:ef: g: ab:s:'
 
Python:
def convert(str):
    # remove whitespace from string
    str = str.replace(" ", "")
    # split the string every 2 characters
    n = 2
    # create a list of every 2 characters in the str.
    result = [str[i:i+n] for i in range(0, len(str), n)]
    # convert the list to a colon-seperated string
    string = ":".join(result)
    # return the result
    return string
 
thank you for the help.
very nice code but still i have the same problem
i dont want to move the white space .
for example..
[he is very smart and i love ] i want to return
'he: is: ve:ry: sm:ar:t: an:d: i: lo:ve:'
 
finaly!!! this i think is run well

Python:
def finaly(sen) :
    
    a = sen
    b = a.split()
    n = 2
    v = 0
    d = ''
    while ( v < len(b) ) :
        result = [b[v][i:i+n] for i in range(0, len(b[v]) +2 , n)]
        
        c = ":".join(result)
        d = d + ' ' + c
        v = v + 1   
    return d[1:]
 
Back
Top