【问题标题】:Extracting a substring just after - in Python [duplicate]在 Python [重复] 之后提取子字符串
【发布时间】:2019-08-08 14:26:58
【问题描述】:

我有一组这样的字符串:

span-aud-result-nhd34-124
span-aud-result-jsh43-125
span-aud-result-i843-127
span-aud-result-mj43-126

我想提取 -

之后的结束子字符串

例如这样的:

124
125
127
126

问题在于像nhd34, jsh43, i843 这样的子字符串是动态的。那么如何在 -

之后提取结束子字符串

谢谢。

【问题讨论】:

  • 结尾数字的长度可能会有所不同。

标签: python python-3.x


【解决方案1】:

使用split() 拆分- 上的字符串并访问列表的最后一个元素:

x = "span-aud-result-nhd34-124"

print(x.split("-")[-1])

输出:

124

说明:

split 将返回:

["span","aud","result","nhd34","124"]

-1 指的是数组的最后一个索引

【讨论】:

    【解决方案2】:

    另一种方法是查找字符串中最后出现的“-”字符,然后根据该索引对初始字符串进行子集化:

    >>> s = 'span-aud-result-nhd34-124span-aud-result-nhd34-124'
    
    >>> s[(s.rfind('-') + 1):]
    '124'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2020-03-23
      • 2018-07-26
      • 2019-06-22
      • 1970-01-01
      相关资源
      最近更新 更多