Search code examples
pythonstringslicestring-operations

How to grab a substring from a given string?


Basically I have following strings and I want to grab a sub-string from them.

input: RT4_MANGO_AF
output: MANGO

input:  RT4_DF5_WE_APPLE_AF 
output: APPLE 

input: TF_WE_BANANA_AF
output: BANANA

input: RT4_DF5_ORANGE_AF
output: ORANGE

Note the hint here is that, the last 3 chars will remain _AF and I want to grab the sub-string before _AF and after the last-but-one _ symbol.

I have the following code which does the same, but I feel it's not optimal. Is there a way to optimize this code? or can I get optimized code?

sd = 'ER5_WE_APPLE_AF'
m = sd[:-3]
for i in range(len(m)):
    if m[i] == "_":
        si = i
    else:
        continue
m = m[si+1:]
print(m)

Solution

  • Simply writing print(sd.split('_')[-2]) will do the trick. We can do this since the end of the string will always contain "_AF", so we can grab the substring that comes before that.