0

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.

2
  • 3
    you have a tuple, not a string Commented Jul 17, 2011 at 14:19
  • 1
    String is = "This is String" | List = [1,2,3,4,5] | Tuple = (1,2,3,4) Commented Jul 17, 2011 at 14:25

2 Answers 2

5

This gives you the last two terms in your tuple:

>> a = (1,2,3,4)
>> a[-2:]
(3,4)
Sign up to request clarification or add additional context in comments.

1 Comment

at first that didn't work but only because I was converting my tuple to a string (oops). Thanks :)
0

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)

4 Comments

ObWarning: eval() is evil. (In case he doesn't control where the string is coming from).
Nuuuuuu! use ast.literal_eval()
I fully agree with you - it was just a sample in case he has a string mentioned in the question. Sure i know that string could be splited and so on.
@tim: even when you do control where it's coming from, it's evil. You control it; use pickle or json or anything else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.