Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a character at regular intervals in a list

Tags:

python

I am trying to convert 10000000C9ABCDEF to 10:00:00:00:c9:ab:cd:ef

This is needed because 10000000C9ABCDEF format is how I see HBAs or host bust adapaters when I login to my storage arrays. But the SAN Switches understand 10:00:00:00:c9:ab:cd:ef notation.

I have only been able to accomplish till the following:

#script to convert WWNs to lowercase and add the :.
def wwn_convert():
    while True:
        wwn = (input('Enter the WWN or q to quit- '))
        list_wwn = list(wwn)
        list_wwn = [x.lower() for x in list_wwn]
        lower_wwn = ''.join(list_wwn)
        print(lower_wwn)
    if wwn == 'q':
        break

wwn_convert()

I tried ':'.join, but that inserts : after each character, so I get 1:0:0:0:0:0:0:0:c:9:a:b:c:d:e:f

I want the .join to go through a loop where I can say something like for i in range (0, 15, 2) so that it inserts the : after two characters, but not quite sure how to go about it. (Good that Python offers me to loop in steps of 2 or any number that I want.)

Additionally, I will be thankful if someone could direct me to pointers where I could script this better...

Please help.

I am using Python Version 3.2.2 on Windows 7 (64 Bit)

like image 545
pritesh_ugrankar Avatar asked Dec 01 '11 18:12

pritesh_ugrankar


People also ask

How do you put a character after every two characters in a string?

The algorithm is to group the string into pairs, then join them with the - character. The code is written like this. Firstly, it is split into odd digits and even digits. Then the zip function is used to combine them into an iterable of tuples.

How do you add special characters to a string in Python?

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.

How do you add characters after every character in Python?

Using the join() function It can be used to add a character in a string at our desired position. In the above example, we specify the separator character for the join() function as an empty character to avoid any space.


1 Answers

Here is another option:

>>> s = '10000000c9abcdef'
>>> ':'.join(a + b for a, b in zip(*[iter(s)]*2))
'10:00:00:00:c9:ab:cd:ef'

Or even more concise:

>>> import re
>>> ':'.join(re.findall('..', s))
'10:00:00:00:c9:ab:cd:ef'
like image 79
Andrew Clark Avatar answered Nov 09 '22 10:11

Andrew Clark