Take the 2-minute tour ×

I have hunted around various other posts and although there are some useful tips I haven't found a similar problem to mine so I thought I would ask. I have generated the following list:

data2 = ['AN1_OUT,24','AN2_OUT,13','AN3_OUT,14','AN4_OUT,15']

What I want to do is identify the setting (AN1_OUT etc..) and the value (2,13 etc...) that accompanies it. I have successfully identified the setting by using the good old 'if-elif' as I only need to know this setting, however, I now need to separate out the value. So far I am using:

data3 = re.findall('[0-9]{2}',data2[i])
byte1 = map(lambda n: int(n[:2]),data3)

This is in a for loop that runs through all of the elements in the data2 list (4 in this example). for each 'i' I am getting the following:


I know this is what I would expect, however, the problem arises when the value is a single digit such as:


In this case I miss that value and it is not printed. I tried changing the regex in the data3 function to:

data3 = re.findall('[0-9]{1,2}',data2[i])

However the problem with this is that it picks up the digit in AN1_OUT, AN2_OUT etc.. so I end up with:


I have looked at various different ways to solve it but it is proving very elusive. Any help would be appreciated.

share|improve this question
Why not just .split(',')[:-1] to get everything after the comma? –  TyrantWave Sep 19 '13 at 16:32
add comment

3 Answers

up vote 2 down vote accepted

Append $ at the end to make it match only at the end of the input string:


You can use \d instead of [0-9]:


To avoid escape use raw string (r'raw string'):


>>> re.findall(r'\d{1,2}$', 'AN3_OUT,14')

>>> re.findall(r'\d+$', 'AN3_OUT,14')
share|improve this answer
Hey falsetru, that works perfectly, thanks for the detailed explanation. –  AimSkyward Sep 20 '13 at 7:14
add comment

You can use look-behind to fetch the digit preceded by comma. Also, you can use [0-9]+ instead of [0-9]{1,2}, id you can have more digits.

data3 = re.findall(r'(?<=,)[0-9]+',data2[i])
share|improve this answer
add comment

You can parse the strings you've described without using regular expressions. Just split on the comma!

for item in data2:
    setting, value = item.split(',')
    if setting == 'AN1_OUT':
        value = int(value)
        # do stuff with value
share|improve this answer
add comment

Your Answer


