推荐学习书目
› 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 · 3031 views
    This topic created in 3552 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
    okletswin
    Feb 15, 2017
    1
    re.match(r'.*-([^\.]+)\.', 'xxx-102.html')
    fei051466
    fei051466
    Feb 15, 2017❤️1
    2
    >>> target = 'xxx/xxx-102.html'
    >>> result = target[target.find('-') + 1: target.find('.')]
    >>> result
    '102'
    leavic
    leavic
    Feb 15, 2017 via iPhone
    3
    不想用 re 就做两次 split
    zhicheng
    zhicheng
    Feb 15, 2017
    4
    >>> '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
    imn1
    Feb 15, 2017❤️1
    5
    In [4]: import re

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