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?
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?
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(':', '-')
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.