how to convert string to list or tuple

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun May 29 09:32:47 EDT 2005


On Thu, 26 May 2005 19:53:38 +0800, flyaflya wrote:

> a = "(1,2,3)"
> I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', 
> '2', ',', '3', ')') not (1,2,3)

Others have already given some suggestions. Here are some others.

You didn't say where the input string a came from. Do you control
it? Instead of using:

String_Tuple_To_Real_Tuple("(1,2,3)")

can you just create the tuple in the first place?

a = (1, 2, 3)

Second suggestion: if you know that the input string will ALWAYS be in the
form "(1,2,3)" then you can do this:

a = "(1,2,3)"
a = a[1:-1]  # deletes leading and trailing parentheses
a = a.split(",")  # creates a list ["1", "2", "3"] (items are strings)
a = [int(x) for x in a]  # creates a list [1, 2, 3] (items are integers)
a = tuple(a)  # coverts to a tuple

or as a one-liner:

a = "(1,2,3)"
a = tuple([int(x) for x in a[1:-1].split(",")])

Best of all, wrap your logic in a function definition with some
error-checking:

def String_Tuple_To_Real_Tuple(s):
    """Return a tuple of ints from a string that looks like a tuple."""
    if not s:
        return ()
    if (s[0] == "(") and s[-1] == ")"):
        s = s[1:-1]
    else:
        raise ValueError("Missing bracket(s) in string.")
    return tuple([int(x) for x in s.split(",")])


Hope this helps,


-- 
Steven.





More information about the Python-list mailing list