convert a string to tuple

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Jun 2 12:08:24 EDT 2005


On Tue, 31 May 2005 13:14:09 -0700, querypk wrote:

> how do I convert 
> b is a string  b = '(1,2,3,4)' to b = (1,2,3,4)

You can do:

def str2tuple(s):
    """Convert tuple-like strings to real tuples.
    eg '(1,2,3,4)' -> (1, 2, 3, 4)
    """
    if s[0] + s[-1] != "()":
        raise ValueError("Badly formatted string (missing brackets).")
    items = s[1:-1]  # removes the leading and trailing brackets
    items = items.split(',')
    L = [int(x.strip()) for x in items] # clean up spaces, convert to ints
    return tuple(L)

For real production code, you will probably want better error checking.

-- 
Steven.





More information about the Python-list mailing list