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

如何截取字符串?

  •  
  •   ioiioi · 2013-07-15 15:50:07 +08:00 · 3243 次点击
    这是一个创建于 4150 天前的主题,其中的信息可能已经有所发展或是发生改变。
    假设有一个tuple为[['128 MB', '27 PERCENT']]
    我想将128和27全部转换成int,该怎么截取字符串?
    4 条回复    1970-01-01 08:00:00 +08:00
    mrluanma
        1
    mrluanma  
       2013-07-15 16:13:53 +08:00
    >>> [int(x.split(None, 1)[0]) for x in ['128 MB', '27 PERCENT']]
    [128, 27]
    ioiioi
        2
    ioiioi  
    OP
       2013-07-15 16:24:52 +08:00
    @mrluanma
    perfect
    有个疑问,split(None, 1)是啥意思?
    mrluanma
        3
    mrluanma  
       2013-07-15 17:05:19 +08:00
    @ioiioi

    >>> help("".split)

    Help on built-in function split:

    split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string. If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.
    ToughGuy
        4
    ToughGuy  
       2013-07-16 08:58:49 +08:00
    import re

    [map(int, re.findall(r'\d+', x)) for x in ['128 MB', '27 PERCENT']]

    新手...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5814 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 01:53 · PVG 09:53 · LAX 17:53 · JFK 20:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.