-1

i have a .txt file containing mac address with this format f2:e0:e2:e8:3a:5e

how can i convert f2:e0:e2:e8:3a:5e to f2-e0-e2-e8-3a-5e using pyhton and use it as variable?

nicollette16
  • 57
  • 1
  • 8
  • 1
    just replace every `:` with a `-` – Azrael Nov 24 '18 at 10:42
  • @RoadRunner Nope, this works - as my [answer](https://stackoverflow.com/questions/53457318/python-mac-address-convert-format-from-to/53457354#53457354) *should* show - better(faster) than only by replacing - of course replacing works just fine, but if you have to apply this to many addresses(let's say he stores thousands of them in files) then this makes a difference. Worth noting that I also don't need a function call ;) – Luatic Nov 24 '18 at 10:51

2 Answers2

2

Open it with open(), read contents to a string with the .read() method and replace colons with hyphens with the .replace() string method. Store the result in a variable.

mac_addr = open('your_file.txt').read().replace(':', '-')
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 1
    Nice. I would also `close()` the file afterwards, or use a `with` context manager. – RoadRunner Nov 24 '18 at 10:48
  • 2
    @RoadRunner Yes, you could but the file object is now detached from any variable, so we can't throw an error on it and since Python will close the file eventually, I'm happy to leave it. :) – Joe Iddon Nov 24 '18 at 10:56
  • tested this code and it work great. thank your time @JoeIddon – nicollette16 Nov 24 '18 at 11:40
2

Probably(from the idea/complexity) a little faster than Joe's answer(depends on implementation) :

If you can ensure that your address is always in the format xx:xx:xx:xx:xx:xx [...]

with open('your_file.txt') as file:
    address=list(file.read())
    for i in range(2, len(address), 2):
        address[i]="-"
    address="".join(address)
    # do stuff with address here

using with as proposed by RoadRunner. And if you want it blazing fast, look at this : Fast character replacing in Python's immutable strings

This solution will replace every 2nd character with a hyphen.

Luatic
  • 8,513
  • 2
  • 13
  • 34