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
Curtain
V2EX  ›  Python

请教一个字符串截取问题

  •  
  •   Curtain · 2017-02-15 17:08:46 +08:00 · 2015 次点击
    这是一个创建于 2628 天前的主题,其中的信息可能已经有所发展或是发生改变。
    例如 url :
    xxx/xxx-102.html
    xxx/xxx-43.html

    想通过"-"以及"."去定位中字符串并存入列表.
    请问如何实现?
    10 条回复    2017-02-16 17:33:35 +08:00
    okletswin
        1
    okletswin  
       2017-02-15 17:18:41 +08:00
    re.match(r'.*-([^\.]+)\.', 'xxx-102.html')
    fei051466
        2
    fei051466  
       2017-02-15 17:43:58 +08:00   ❤️ 1
    >>> target = 'xxx/xxx-102.html'
    >>> result = target[target.find('-') + 1: target.find('.')]
    >>> result
    '102'
    leavic
        3
    leavic  
       2017-02-15 17:44:51 +08:00 via iPhone
    不想用 re 就做两次 split
    zhicheng
        4
    zhicheng  
       2017-02-15 20:22:18 +08:00
    >>> '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  
       2017-02-15 21:48:18 +08:00   ❤️ 1
    In [4]: import re

    In [5]: re.split(r'[.\-]', 'xxx/xxx-102.html')
    Out[5]: ['xxx/xxx', '102', 'html']
    mringg
        6
    mringg  
       2017-02-15 23:27:58 +08:00 via iPhone
    题主是老司机,鉴定完毕
    Antidictator
        7
    Antidictator  
       2017-02-16 10:16:13 +08:00
    @mringg 你也是老司机鉴定完毕
    Curtain
        8
    Curtain  
    OP
       2017-02-16 11:27:27 +08:00
    @imn1 好用。谢谢
    ijustdo
        9
    ijustdo  
       2017-02-16 17:30:52 +08:00
    >>> a = 'xxx/xxx-102.html'
    >>> a.rsplit('.', 1)[0].rsplit('-', 1)[-1]
    ijustdo
        10
    ijustdo  
       2017-02-16 17:33:35 +08:00
    大家要考虑 xxx/xxx 里面也可能包含 . 或者 - 的情况 呵呵 永远不要相信任何输入
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1165 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:32 · PVG 07:32 · LAX 16:32 · JFK 19:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.