1

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']
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3761151
  • 143
  • 1
  • 7

5 Answers5

2

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'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
2

You should use the join method:

",".join(m['value'].split(', ')[0:2:])
Thomas Cokelaer
  • 1,049
  • 1
  • 8
  • 11
0
array = ['S/M - Black', ' 93094-01']
string = ','.join(array)
Magnus Buvarp
  • 976
  • 7
  • 19
0

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

Community
  • 1
  • 1
Nike
  • 72
  • 6
0
list1 = ['S/M - Black', ' 93094-01']
str1 = ''.join(str(e) for e in list1)
user3273866
  • 594
  • 4
  • 8