zoukankan      html  css  js  c++  java
  • python基础===正则表达式,常用函数re.split和re.sub

    sub的用法:

    >>> rs = r'c..t'
    
    >>> re.sub(rs,'python','scvt dsss cvrt pocdst')
    'scvt dsss python popython'
    

     可以将c..t格式的字符串全部替换为python

    同理说一下,python字符串函数replace的用法:

    >>> s = 'hello china'
    >>> s.replace('hello','love')
    'love china'
    >>> s
    'hello china'
    

     split的用法:

    >>> ip = '1,2,3,4'
    >>> ip.split(',')
    ['1', '2', '3', '4']
    >>> 
    

     re.split的用法,

    >>> s = '123+345-343*787/33'
    >>> re.split(r'[+-*/]',s)
    ['123', '345', '343', '787', '33']
    

     加反斜杠是因为,+-*在正则中都有含义,如果不加反斜杠,语法错误

    这样就可以从算式中提取到数据

  • 相关阅读:
    Linux命令
    Linux目录说明
    python推导式
    python公共方法
    python集合
    python字典
    python元组
    python列表
    python字符串常用操作方法
    C语言编译过程
  • 原文地址:https://www.cnblogs.com/botoo/p/7413347.html
Copyright © 2011-2022 走看看