Home > Enterprise >  Python Convert list of tuple in to string containing different types of format
Python Convert list of tuple in to string containing different types of format

Time:09-22

I want to convert below list of tuple into single string, where output string should replace datetime obj into string datetime format None should be replace with 'None' and integer should be replace with str(int)

rows = [('name', 25,  datetime.datetime(2018, 1, 9, 0, 0, 1), None), ('name2', 26,  datetime.datetime(2018, 1, 9, 0, 0, 1), None)]

I want below out put as string

'(('name', '25',  '2018-01-09 00:00:01', 'None'), ('name2', '26',  2018-01-09 00:00:01, 'None')]'

expectation :

'((str, str, str, str), (str, str, str, str))'

I tried following

print('(%s)' % ','.join(str(i) for i in rows  ))

but it is not converting in proper format. I am missing something

CodePudding user response:

import datetime
rows = [('name', 25,  datetime.datetime(2018, 1, 9, 0, 0, 1), None), ('name2', 26,  datetime.datetime(2018, 1, 9, 0, 0, 1), None)]
print(str(tuple(tuple(map(str, item)) for item in rows)))

or if your prefer list comprehension instead of map()

print(str(tuple(tuple(str(ele) for ele in item) for item in rows)))

CodePudding user response:

It looks like your code is converting each tuple within the list to str, rather than each item within the tuples.

This line will convert each item in the tuple to str, using tuples and generator expressions:

>>> str(tuple(tuple(str(x) for x in r) for r in rows))
"(('name', '25', '2018-01-09 00:00:01', 'None'), ('name2', '26', '2018-01-09 00:00:01', 'None'))"

Note that there are two for keywords, to traverse both levels of your structure.

  • Related