V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
Curtain
V2EX  ›  Python

请教一个字符串截取问题

  •  
  •   Curtain · Feb 15, 2017 · 2552 views
    This topic created in 3357 days ago, the information mentioned may be changed or developed.
    例如 url :
    xxx/xxx-102.html
    xxx/xxx-43.html

    想通过"-"以及"."去定位中字符串并存入列表.
    请问如何实现?
    10 replies    2017-02-16 17:33:35 +08:00
    okletswin
        1
    okletswin  
       Feb 15, 2017
    re.match(r'.*-([^\.]+)\.', 'xxx-102.html')
    fei051466
        2
    fei051466  
       Feb 15, 2017   ❤️ 1
    >>> target = 'xxx/xxx-102.html'
    >>> result = target[target.find('-') + 1: target.find('.')]
    >>> result
    '102'
    leavic
        3
    leavic  
       Feb 15, 2017 via iPhone
    不想用 re 就做两次 split
    zhicheng
        4
    zhicheng  
       Feb 15, 2017
    >>> 'xxx/xxx-102.html'.rpartition('-')[2].partition('.')[0]
    '102'
    >>> 'xxx/xxx-43.html'.rpartition('-')[2].partition('.')[0]
    '43'
    >>> ''.rpartition('-')[2].partition('.')[0]
    ''
    >>> '-------------'.rpartition('-')[2].partition('.')[0]
    ''
    >>> '.........'.rpartition('-')[2].partition('.')[0]
    ''
    >>> '-.-.-.-.-.-.'.rpartition('-')[2].partition('.')[0]
    ''
    >>> '-123.-456.-789.-123.-456.-789.'.rpartition('-')[2].partition('.')[0]
    '789'
    >>> 'laksdjflkajs8923u41--..asdf92u34100---12342.'.rpartition('-')[2].partition('.')[0]
    '12342'
    imn1
        5
    imn1  
       Feb 15, 2017   ❤️ 1
    In [4]: import re

    In [5]: re.split(r'[.\-]', 'xxx/xxx-102.html')
    Out[5]: ['xxx/xxx', '102', 'html']
    ming2050
        6
    ming2050  
       Feb 15, 2017 via iPhone
    题主是老司机,鉴定完毕
    Antidictator
        7
    Antidictator  
       Feb 16, 2017
    @mringg 你也是老司机鉴定完毕
    Curtain
        8
    Curtain  
    OP
       Feb 16, 2017
    @imn1 好用。谢谢
    ijustdo
        9
    ijustdo  
       Feb 16, 2017
    >>> a = 'xxx/xxx-102.html'
    >>> a.rsplit('.', 1)[0].rsplit('-', 1)[-1]
    ijustdo
        10
    ijustdo  
       Feb 16, 2017
    大家要考虑 xxx/xxx 里面也可能包含 . 或者 - 的情况 呵呵 永远不要相信任何输入
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   937 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 22:39 · PVG 06:39 · LAX 15:39 · JFK 18:39
    ♥ Do have faith in what you're doing.