zoukankan      html  css  js  c++  java
  • 将字符串分片

    RegexObject 的 split() 方法在 RE 匹配的地方将字符串分片,将返回列表。它同字符串的 split() 方法相似但提供更多的定界符;split()只支持空白符和固定字符串。就象你预料的那样,也有一个模块级的 re.split() 函数。

    split(string [, maxsplit = 0])
    

    通过正则表达式将字符串分片。如果捕获括号在 RE 中使用,那么它们的内容也会作为结果列表的一部分返回。如果 maxsplit 非零,那么最多只能分出 maxsplit 个分片。

    你可以通过设置 maxsplit 值来限制分片数。当 maxsplit 非零时,最多只能有 maxsplit 个分片,字符串的其余部分被做为列表的最后部分返回。在下面的例子中,定界符可以是非数字字母字符的任意序列。

    #!python
    >>> p = re.compile(r'W+')
    >>> p.split('This is a test, short and sweet, of split().')
    ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
    >>> p.split('This is a test, short and sweet, of split().', 3)
    ['This', 'is', 'a', 'test, short and sweet, of split().']
    

    有时,你不仅对定界符之间的文本感兴趣,也需要知道定界符是什么。如果捕获括号在 RE 中使用,那么它们的值也会当作列表的一部分返回。比较下面的调用:

    #!python
    >>> p = re.compile(r'W+')
    >>> p2 = re.compile(r'(W+)')
    >>> p.split('This... is a test.')
    ['This', 'is', 'a', 'test', '']
    >>> p2.split('This... is a test.')
    ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
    

    模块级函数 re.split() 将 RE 作为第一个参数,其他一样。

    #!python
    >>> re.split('[W]+', 'Words, words, words.')
    ['Words', 'words', 'words', '']
    >>> re.split('([W]+)', 'Words, words, words.')
    ['Words', ', ', 'words', ', ', 'words', '.', '']
    >>> re.split('[W]+', 'Words, words, words.', 1)
    ['Words', 'words, words.']
  • 相关阅读:
    PhpExcel笔记,phpExcel中文帮助手册
    mysql “group by ”与"order by"的研究--分类中最新的内容
    mysql中,主键与普通索引
    mysql性能优化-慢查询分析、优化索引和配置
    OpenSSL
    HAProxy
    Lighttpd
    Linux find/grep命令
    keepalived
    iptables
  • 原文地址:https://www.cnblogs.com/kuihua/p/5971025.html
Copyright © 2011-2022 走看看