0

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:

[24]
[13]
[14]
[15]

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

'AN1_OUT,2' 

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:

[1,2]
[2,13]
[3,14]
[4,15]

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

1
  • 1
    Why not just .split(',')[:-1] to get everything after the comma? Commented Sep 19, 2013 at 16:32

3 Answers 3

2

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

'[0-9]{1,2}$'

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

'\\d{1,2}$'

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

r'\d{1,2}$'

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

>>> re.findall(r'\d+$', 'AN3_OUT,14')
['14']
Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.