zoukankan      html  css  js  c++  java
  • python-一种去掉前后缀获取子串的方法

    假设有一个字符串,其数据组成方式为:"mode_id1_str_id2",其中id1和id2为任意个数的数字,若存在mode,则id1必然也存在,否则都不存在;id2可有可没有。

    如这些字符串满足条件:s1 = 'mode_0_string1_1',s2 = 'string2', s3 = 'mode_1_string3' , s4 = 'string4_12'。

    目的:去掉mode_id1和id2,也就是去掉满足某种条件的字符串的前缀和后缀,或者到中间的字符串。如上面的例子中,获取的字符串分别为:string1、string2、string3、string4。

    函数实现如下:

     1    s1 = 'mode_0_string1_1'
     2    s2 = 'string2'
     3    s3 = 'mode_1_string3'
     4    s4 = 'string4_12'
     5    mode = 'mode'
     6    for s in [s1, s2, s3, s4]:
     7       prefix = re.match(mode+'_d+', s)
     8       if bool(prefix) == True:
     9          prefix_string = prefix.group()
    10          prefix_index = len(prefix_string)
    11          drop_prefix = s[prefix_index+1:]
    12       else:
    13          drop_prefix = s
    14       # 去掉后缀
    15       s_tmp = drop_prefix[::-1]
    16       suffix = re.match('d+_', s_tmp)
    17       if bool(suffix) == True:
    18          suffix_index = len(suffix.group())
    19          suffix_string = drop_prefix[-suffix_index:]
    20          drop_suffix = drop_prefix[:-suffix_index]
    21       else:
    22          drop_suffix = drop_prefix
    23       print (drop_suffix)

    输出结果:

    1 string1
    2 string2
    3 string3
    4 string4

    这个函数其实没有普遍的使用意义,在这里只是想说明我们要匹配字符串尾部的字符串时,可以使用string[::-1]的方式先将字符串反过来,再当作处理一般的字符串首部就行了。

  • 相关阅读:
    hdu4930 Fighting the Landlords(模拟 多校6)
    hdu4888 多校B 最大流以及最大流唯一推断+输出方案
    xUtils介绍 -- DbUtils、ViewUtils、HttpUtils、BitmapUtils
    java 读取properties文件
    poj1062昂贵的聘礼
    杭电 HDU 2717 Catch That Cow
    iOS使用自己定义字体
    Elasticsearch 2014年10月简报
    html 上下左右都居中
    Linux 比较判断运算(if else)
  • 原文地址:https://www.cnblogs.com/mrlayfolk/p/12577734.html
Copyright © 2011-2022 走看看