On 24/07/18 08:25, Mark Lawrence wrote: > On 24/07/18 06:41, Sayth Renshaw wrote: >> On Tuesday, 24 July 2018 14:25:48 UTC+10, Rick Johnson wrote: >>> Sayth Renshaw wrote: >>> >>>> elements = [['[{0}]'.format(element) for element in elements]for >>>> elements in data] >>> >>> I would suggest you avoid list comprehensions until you master >>> long-form loops. >> >> I actually have the answer except for a glitch where on list element >> is an int. >> >> My code >> >> for item in data: >> out = '[{0}]'.format("][".join(item)) >> print(out) >> >> which prints out >> >> [glossary] >> [glossary][title] >> [glossary][GlossDiv] >> [glossary][GlossDiv][title] >> [glossary][GlossDiv][GlossList] >> .... >> >> However, in my source I have two lines like this >> >> ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', >> 'GlossSeeAlso', 0], >> ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', >> 'GlossSeeAlso', 1], >> >> when it hits these lines I get >> >> TypeError: sequence item 6: expected str instance, int found >> >> Do I need to do an explicit check for these 2 cases or is there a >> simpler way? >> >> Cheers >> >> Sayth >> > > out = '[{0}]'.format("][".join(str(item)))
No. >>> item = ['a', 'b', 1] >>> '[{0}]'.format("][".join(item)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 2: expected str instance, int found >>> '[{0}]'.format("][".join(str(item))) "[[]['][a]['][,][ ]['][b]['][,][ ][1][]]" >>> You'll want to use map(), a generator comprehension, or a different approach. > -- https://mail.python.org/mailman/listinfo/python-list