zoukankan      html  css  js  c++  java
  • 字符串常用处理方法

    lstrip()

      lstrip()去除字符串左边的空格,也可使用lstrip('#')去除字符串左边的"#"等

    s=' A B C D '
    # 去除左边空格
    print(s.lstrip())

    rstrip()

      rstrip()去除字符串右边的空格,也可使用rstrip('#')去除字符串左边的"#"等

    s=' A B C D '
    # 去除右边空格
    print(s.rstrip())

    strip()

      去除左右两边的空格,也可使用strip('#')去除字符串左右两边的"#"等

    s=' A B C D '
    # 去除左右两边空格
    print(s.strip())

    re.sub

      使用正则表达式去除字符串中所有的空格

    import re
    s=' A B C D '
    print(re.sub('s','',s))

    split()

      分割字符串,可以使用指定字符分割字符串(s.split('a'))

    s=' A B C D '
    # 以空格分隔字符串
    print(s.split())

      多种分割,指定的分割字符串不唯一时可以使用正则表达式分割

    # 多种分割
    time=' 2018/07/02 15:35:20'
    print(re.split(r'[/s:]+',time.strip()))

    

      使用查找字符串,匹配一个单词边界,也就是指单词和空格间的位置,例如'lo'可以匹配‘hello’中的‘lo’,但不能匹配'loli'中的'lo'

    #使用查找指定字符
    context='''
    When I was One
    I had just begun
    When I was Two
    I was nearly new
    '''
    print(re.findall(r'was',context.lower()))

    B

      匹配非单词边界,例如'loB'可以匹配'loli'中的'lo',但不能匹配‘hello’中的‘lo’

    #使用B查找指定字符
    context='''
    When I was One
    I had just begun
    When I was Two
    I was nearly new
    '''
    print(re.findall(r'nearB',context.lower()))
  • 相关阅读:
    iOS中的imageIO与image解码
    在asp.net 中生成PDF的方法
    asp.net中模拟测试smtp发邮件
    ASP.NET导入EXCEL方法汇总
    在asp.net中使用加密数据库联接字符串
    CSS实现限制字数功能
    在ASP.NET中备份和还原数据库
    说说ASP.NET的IsPostBack
    javascript小技巧之with()方法
    CSS中filter滤镜的学习笔记
  • 原文地址:https://www.cnblogs.com/iamluoli/p/9254159.html
Copyright © 2011-2022 走看看