The return character was causing it to skip the first part, you can see the difference by using repr
>>> print ",".join(array)
,monkey,pig
>>> print repr(",".join(array))
'dog\r,monkey,pig'
Use map
and strip
to remove the return character
>>> array=['dog\r', 'monkey', 'pig']
>>> ",".join(map(str.strip,array))
The output is
'dog,monkey,pig'
Note that it is slightly better to use map
rather than a comprehension to strip characters. The timeit
results
$ python -m timeit "','.join(s.strip() for s in ['dog\r', 'monkey', 'pig'])"
1000000 loops, best of 3: 1.18 usec per loop
$ python -m timeit "','.join(map(str.strip,['dog\r', 'monkey', 'pig']))"
1000000 loops, best of 3: 0.647 usec per loop
The use of map
vs comprehensions is discussed here.
The most popular (and accepted answer) conclusion is quoted here:
map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp).