Kevin
Kevin

Reputation: 1085

Issue with join(str(x))

x = [1,2,3]  
print '-'.join(str(x))

Expected:

1-2-3

Actual:

(-1-,- -2-,- -3-)

What is going on here?

Upvotes: -1

Views: 63

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49320

You sent x to str() first, putting the given delimiter between each character of the string representation of that whole list. Don't do that. Send each individual item to str().

>>> x = [1,2,3]
>>> print '-'.join(map(str, x))
1-2-3

Upvotes: 1

idjaw
idjaw

Reputation: 26560

Because calling str on the list in its entirety gives the entire list as a string:

>>> str([1,2,3])
'[1, 2, 3]'

What you need to do is cast each item in the string to an str, then do the join:

>>> '-'.join([str(i) for i in x])
'1-2-3'

Upvotes: 2

Related Questions