90abyss
90abyss

Reputation: 7347

Remove square brackets from list

I have this list:

list1 = [['123'], ['456'], ['789']]

I want to convert this list into a string and later store it into a column in a database in this form:

123 / 456 / 789

I tried doing this:

s2 = ", ".join(repr(e) for e in list1)
print(s2)

But this is what I'm getting:

['123'], ['456'], ['789']

Any ideas on what should I do next to get the desired output?

Upvotes: 0

Views: 17215

Answers (5)

idjaw
idjaw

Reputation: 26578

You are close, but what you want to do is flatten your list of lists first, then convert to string. Like this:

" / ".join([item for sublist in list1 for item in sublist])

Upvotes: 8

nigel222
nigel222

Reputation: 8202

If you specifically only ever want the first element of a sublist even if it's got more than one element, then I think this one-liner is the clearest:

s2 = ' / '.join(  x[0] for x in list1 )

Upvotes: 0

LetzerWille
LetzerWille

Reputation: 5658

list1 = [['123'], ['456'], ['789']]

st = [ '/' + x[0]  for x in list1]

st = ''.join(st)

print(st)

output

/123/456/789

Upvotes: 1

Ozan
Ozan

Reputation: 1074

Since you have lists in the list, you need to get the first indice so this helps you

" / ".join(map(lambda x:x[0],list1))

Upvotes: 0

Aldehir
Aldehir

Reputation: 2053

You can use itertools.chain

import itertools

list1 = [['123'], ['456'], ['789']]
", ".join(itertools.chain(*list1))
# => '123, 456, 789'

Upvotes: 1

Related Questions