Convert python list of string to bytearray
<p>I would write a list on serial COM through pySerial.</p>

<p>I create a list of string, where each string is a parameter, and then I pass the list to serial write function. There is an error because I cannot write list of string directly on serial</p>

<p>This is my code:</p>

<pre><code>import datetime
import time
import sys
import serial

date = datetime.datetime.now()
dateStr = str(date.strftime('%d-%m-%Y'))
unixTime = int(time.time())
crc = str("1234")


packet = list()

packet.append('test')
packet.append(dateStr)
packet.append(unixTime)
packet.append('4')
packet.append('81')
packet.append('1')
packet.append('0')

packet.append('00.7')
packet.append('4')
packet.append('9')
packet.append('0')

packet.append('18.8')
packet.append('5')
packet.append('3')
packet.append('0')

packet.append('15.3')
packet.append('4')
packet.append('6')
packet.append('0')

packet.append('2')
packet.append('0')
packet.append('13')
packet.append('0')

packet.append('0')
packet.append('0')
packet.append('185.6')

# add semicolon between list elements
serialCOM.write(packet)
</code></pre>

<p>Is there a way to concatenate each list elements into a list or bytearray?</p>

<p>Furthermore I need to add a semicolon between each list elements.</p>

<p>Thanks for the help!</p>

<p>If you want an actual bytearray object, pass the list into the bytearray constructor. </p>

<pre><code>serialCOM.write(bytearray(packet))
</code></pre>

<p>Note that <code>unixTime</code> is not converted to a string so you must convert that first.</p>

<p>But what you probably want (based on the comment about semicolons) is to just join the strings using the join method of a string like this:</p>

<pre><code># Force all items in the list to be strings
msg = ';'.join(map(str,packet))
serialCOM.write(msg)
</code></pre>

<p>The result of the join is then:</p>

<pre><code>In[50]: ';'.join(map(str,packet))
Out[50]: 'test;17-10-2016;1476708605;4;81;1;0;00.7;4;9;0;18.8;5;3;0;15.3;4;6;0;2;0;13;0;0;0;185.6'
</code></pre>

python python-2.7 type-conversion concatenation pyserial