user3761151
user3761151

Reputation: 143

Concatenation of items in list

I have such a list:

['S/M - Black', ' 93094-01']

It is the result of:

m['value'].split(',')[0:2:]

How can I produce such a string from it:

'S/M - Black, 93094-01'

I have tried:

print [i + ', ' + i for i in m['value'].split(', ')[0:2:]]

But it gives me:

['S/M - Black, S/M - Black', ' 93094-01,  93094-01']

Upvotes: 1

Views: 175

Answers (5)

user3273866
user3273866

Reputation: 604

list1 = ['S/M - Black', ' 93094-01']
str1 = ''.join(str(e) for e in list1)

Upvotes: 0

Nike
Nike

Reputation: 72

The .split function returns a list, read docs here https://docs.python.org/2/library/stdtypes.html

So you can join you're list values by using ','.join(['S/M - Black', ' 93094-01']) as answered earlier on a similar question Concatenate item in list to strings

Upvotes: 0

Thomas Cokelaer
Thomas Cokelaer

Reputation: 1059

You should use the join method:

",".join(m['value'].split(', ')[0:2:])

Upvotes: 2

Magnus Buvarp
Magnus Buvarp

Reputation: 976

array = ['S/M - Black', ' 93094-01']
string = ','.join(array)

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 121973

As you have seen,

[i + ', ' + i for i in m['value'].split(', ')[0:2:]]

applies that format to each item in turn. Instead, you want:

", ".join(m['value'].split(",")[:2])

(note the neater slice, which means "the first two items"). For example:

>>> ", ".join(['S/M - Black', ' 93094-01'])
'S/M - Black,  93094-01'

Upvotes: 2

Related Questions