0

I have a requirement to add 2 string which are in mac format as hex which has 9 octets. As part of that I have achieved almost, but one final thing pending is to get the value in 2 digit format.

string1= "aa.aa.aa.aa.aa.aa.aa.aa.ff"
string2= "00.00.00.00.00.00.00.00.01" 

when I add these 2 the out put I get is aa.aa.aa.aa.aa.aa.aa.ab.0 but I want value to be aa.aa.aa.aa.aa.aa.aa.ab.00 . (2 zeros).

I tried using

temp = '%02d' % string3 

but I got error

TypeError: %d format: a number is required, not str

as I am trying to do that with string.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Ravi Kiran
  • 27
  • 5

2 Answers2

1

You can split the string, pad each part with leading zeros and join it again:

s = "aa.aa.aa.aa.aa.aa.aa.ab.0"
print '.'.join(["{0:0>2}".format(w) for w in s.split('.')])

Output:

aa.aa.aa.aa.aa.aa.aa.ab.00

(The padding is based on this answer.)


Even shorter version based on map:

print '.'.join(map("{0:0>2}".format, s.split('.')))
Community
  • 1
  • 1
Falko
  • 17,076
  • 13
  • 60
  • 105
  • Thank you so much Falko. It worked. Which one is better among both methods? Padding or map based? – Ravi Kiran Aug 02 '15 at 08:31
  • The `format` function does the padding. So the difference is using a [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) or the `map` function. In my point of view it doesn't really matter which one to use here. With `map` you save a temporary variable, which might improve readability. – Falko Aug 02 '15 at 08:33
0

Instead of fixing the resulting string3, you can improve the way you create it. If you convert the summands to integers, add them and convert the result back to a hex representation, you don't have to worry about missing zeros:

a = "aa.aa.aa.aa.aa.aa.aa.aa.ff"
b = "00.00.00.00.00.00.00.00.01"
c = hex(int(a.replace('.', ''), 16) + int(b.replace('.', ''), 16))[2:-1]
print '.'.join(i+j for i,j in zip(c[::2], c[1::2]))

Output:

aa.aa.aa.aa.aa.aa.aa.ab.00

References:

Community
  • 1
  • 1
Falko
  • 17,076
  • 13
  • 60
  • 105
  • This is awesome. I have around 15 lines of code to do this. but you made in just 3 lines...Genius. Thanks again. – Ravi Kiran Aug 02 '15 at 08:36