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()))
  • 相关阅读:
    Educational Codeforces Round 58 A,B,C,D,E,G
    Codeforces Round #530 (Div. 2) F (树形dp+线段树)
    Codeforces Round #530 (Div. 2) A,B,C,D
    bzoj 3262: 陌上花开
    bzoj 2653: middle (主席树+二分)
    费马小定理的证明
    分组背包
    二维费用的背包问题
    luoguP1164 小A点菜(背包问题)
    完全背包问题
  • 原文地址:https://www.cnblogs.com/iamluoli/p/9254159.html
Copyright © 2011-2022 走看看