推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
ppj
V2EX  ›  Python

Python 每日一练:等分字符串

  •  
  •   ppj · Aug 12, 2022 · 4373 views
    This topic created in 1507 days ago, the information mentioned may be changed or developed.

    Python 每日一练 => 等分字符串

    import re
    
    # 'F0-B4-29-98-CE-34'
    '-'.join(re.findall(r'.{2}', 'F0B42998CE34'))
    

    使用场景:字符串平均切割、MAC 地址切割等操作。

    8 replies  •  2022-08-19 16:23:18 +08:00
    krixaar
        1
    krixaar  
       Aug 12, 2022   ❤️ 13
    from textwrap import wrap

    # 'F0-B4-29-98-CE-34'
    '-'.join(wrap('F0B42998CE34', 2))
    ppj
        2
    ppj  
    OP
       Aug 12, 2022
    @krixaar 嗯嗯,多谢哈。
    wang9571
        3
    wang9571  
       Aug 12, 2022   ❤️ 2
    '-'.join(s[x:x+2] for x in range(0, len(s), 2))
    Geekgogo
        4
    Geekgogo  
       Aug 12, 2022
    @krixaar #1 学到老活到老
    piglei
        5
    piglei  
       Aug 12, 2022
    好答案前面有了,我再多贡献一条基于正则的花活。若干年前学自《精通正则表达式》,对于当时的我过于震撼,牢记至今:

    >>> s = 'F0B42998CE34'
    >>> import re
    >>> re.sub(r'(?<=.)(?=(..)+$)', '-', s)
    'F0-B4-29-98-CE-34'
    luckyc
        6
    luckyc  
       Aug 13, 2022
    string='20220202'
    # out put-> 2022-02-02
    楼下的请解答
    elboble
        7
    elboble  
       Aug 13, 2022
    ''.join([(str[i]+('-' if i%2 and not (i==1 or i == len(str)-1) else '')) for i in range(len(str))])
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5511 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 02:50 · PVG 10:50 · LAX 19:50 · JFK 22:50
    ♥ Do have faith in what you're doing.