Split python strings by Fixed Length

Source: Internet
Author: User

Today, a colleague gave me a bunch of mac addresses that need to be changed to a certain format. For example, if mac = '902b345fb021 'is changed to mac = '90-2B-34-5F-B0-21', he wrote a small python script, help. In fact, the string is split according to a fixed length.

There are a bunch of mac addresses in the mac.txt file: There are two methods to implement the scheme:
 
 
  1. Method 1:
  2. Aw.open('mac.txt ', 'R ')
  3. A = A. readlines ()
  4. Foraaina:
  5. B = list (aa. strip ())
  6. C =''
  7. Foriinrange (len (B )):
  8. Ifi! = 0:
  9. Ifi % 2 = 0:
  10. C = c + '-' + B [I]
  11. Else:
  12. C = c + B [I]
  13. Else:
  14. C = c + B [I]
  15. Printc
  16. A. close ()
  17. This method is relatively simple. It was just thought of at first.
  18. Method 2:
  19. Importre
  20. Aw.open('mac.txt ', 'R ')
  21. A = A. readlines ()
  22. Foraaina:
  23. B = re. findall (R'. {2} ', aa)
  24. C = '-'. join (B)
  25. Printc
  26. A. close ()
  27. This method is implemented using python regular expressions, which is convenient and highly efficient in execution.

The processing result is as follows:

50-E5-49-E3-2E-CB

90-2B-34-13-EF-A6

50-E5-49-EC-BA-1C

90-2B-34-57-B1-6F

1C-6F-65-29-6D-F9

90-2B-34-13-1A-14

50-E5-49-E3-E2-F8

50-E5-49-3A-26-96

90-2B-34-5F-B0-21

90-2B-34-13-15-74

90-2B-34-18-43-BF

00-24-1D-0E-25-8D

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.