Read Strings in Python
<p>I have some values in a string </p>

<pre><code>[AD6:0.02] [AD7:0.03] [AD8:0.19][AD3:6][AD0:22][AD1:22][AD4:48.00][AD5:0.01] [AD6:0.03]
</code></pre>

<p>I just want to read the values of each 'AD' like 0.02 in AD6 for example. The string changes each time, so I cannot use 'substring'.</p>

<p>Here is my code</p>

<pre><code>while True:

    data = ser.read(9999)

    for x in data:
        if ((x==':') &amp; (x+1=='0')):
            print 'Achou'
</code></pre>

<p>Does someone have an idea about how I can extract the value of each AD and put it in a variable ? (The is in a loop).</p>

<p>Use <code>re.findall()</code> with a proper regex:</p>

<pre><code>In [80]: s = "[AD6:0.02] [AD7:0.03] [AD8:0.19][AD3:6][AD0:22][AD1:22][AD4:48.00][AD5:0.01] [AD6:0.03]"

In [81]: regex = re.compile(r'AD\d:([\d.]+)')

In [82]: regex.findall(s)
Out[82]: ['0.02', '0.03', '0.19', '6', '22', '22', '48.00', '0.01', '0.03']
</code></pre>

<p>If you want to convert the values to float you better to use <code>finditer()</code> that returns an iterator-like object and convert the matched groups to float using <code>float()</code> within a list comprehension:</p>

<pre><code>In [85]: [float(x.group(1)) for x in regex.finditer(s)]
Out[85]: [0.02, 0.03, 0.19, 6.0, 22.0, 22.0, 48.0, 0.01, 0.03]
</code></pre>

<p>But note that this might raise a <code>ValueError</code> if your number are not valid digits. In that case you better to use a regular loop and handle the exceptions with a <code>try-except</code> expression. </p>

python string