hef
hef

Reputation: 19

how do i extract a partial value from a string in python?

I have the following string:

(1, 2, 3, 4)

I want to convert it to just the last two values:

(3, 4)

In my actual code all four fields are whole numbers but vary greatly in length. I've tried doing this with both regex and 'for' statements as well as trying the various answers to similar questions here on SO but so far no luck.

Upvotes: 0

Views: 193

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

If (1,2,3,4) is tuple:

data = (1,2,3,4)
newData = data[-2:]

If you have '(1,2,3,4)' then:

import ast
data = ast.literal_eval('(1,2,3,5)')
newData = data[-2:]

Or in case you have to split such list in a certain value:

def get_slice(inputData, searchVal):   
    if searchVal in inputData and inputData.index(searchVal) < len(inputData):
        return inputData[inputData.index(searchVal)+1:]
    return ()

get_slice((1,2,3,4),2)

Upvotes: 0

joaquin
joaquin

Reputation: 85663

This gives you the last two terms in your tuple:

>> a = (1,2,3,4)
>> a[-2:]
(3,4)

Upvotes: 5

Related Questions