V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2022-08-12 11:16:31 +08:00 · 2889 次点击
    这是一个创建于 615 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    8 条回复    2022-08-19 16:23:18 +08:00
    krixaar
        1
    krixaar  
       2022-08-12 11:39:28 +08:00   ❤️ 13
    from textwrap import wrap

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

    >>> s = 'F0B42998CE34'
    >>> import re
    >>> re.sub(r'(?<=.)(?=(..)+$)', '-', s)
    'F0-B4-29-98-CE-34'
    l4ever
        6
    l4ever  
       2022-08-13 19:22:35 +08:00
    string='20220202'
    # out put-> 2022-02-02
    楼下的请解答
    elboble
        7
    elboble  
       2022-08-13 22:50:18 +08:00
    ''.join([(str[i]+('-' if i%2 and not (i==1 or i == len(str)-1) else '')) for i in range(len(str))])
    brucmao
        8
    brucmao  
       2022-08-19 16:23:18 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5894 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 06:20 · PVG 14:20 · LAX 23:20 · JFK 02:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.