2

I have a set of strings like this:

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

I want to extract the ending substring after -

For Example like this:

124
125
127
126

The problem is that the substrings like nhd34, jsh43, i843 are dynamic. So how can I extract the ending substring just after -

Thanks.

Sociopath
  • 13,068
  • 19
  • 47
  • 75

2 Answers2

6

Use split() to split the string on - and access last element of list:

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

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

Output:

124

Explanation:

the split will return:

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

-1 refers to the last index of an array

Sociopath
  • 13,068
  • 19
  • 47
  • 75
1

Another way is to find the last occurrence of the '-' character in your string and then subset your initial string based on that index:

>>> s = 'span-aud-result-nhd34-124span-aud-result-nhd34-124'

>>> s[(s.rfind('-') + 1):]
'124'
dvitsios
  • 458
  • 2
  • 7