6

I wanted to convert the integer of tuple into string of tuple. For example:

data = [(2,3,4,...),(23,42,54,...),......]

would result in:

d = [('2','3','4',...),('23','42','54',....)......]

Please notice how tuple is big and list is also big.

I tried the code below but it doesn't give me the result I was looking for:

data = [(2,3,4,...),(23,42,54,...),......] 

d=[]
for t in data:
    d.append(str(t))

2 Answers 2

10

This gets close:

data = [[str(x) for x in tup] for tup in data]

If you actually need tuples:

data = [tuple(str(x) for x in tup) for tup in data]

Or, if you prefer a more "functional" approach:

data = [tuple(map(str, tup)) for tup in data]

Though it seems that map has fallen out of favor with the python crowd (or maybe it never was actually in favor ;-).

Sign up to request clarification or add additional context in comments.

Comments

0

This will recursively convert infinitely nested lists and tuples:

def stringify(something):
    if type(something) == list:
        return [stringify(x) for x in something]
    elif type(something) == tuple:
        return tuple(stringify(list(something)))
    else:
        return str(something)

1 Comment

Careful throwing around the term "infinitely" -- You'll run into a recursion limit sometime, at least in most python implementations. I'm not sure about stackless . . . Hmm . . . :-)

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.