简体   繁体   中英

Extracting numbers from a string in python 1.5.2

I'm currently working with a Telit module (GT864-py) and I'm trying to extract numbers from a return value/string that I recieve when using AT-commands.

This is an example of the code that I'm using:

MDM.send('AT#ADC=1,2'+'\r', 5)
pump = MDM.receive(15)
pumpb = int(filter(str.isdigit, pump))

which gives the response

#ADC: 10 (This number can range from ~10-150)
OK

Now, I would like to filter the number after ADC, however, I have not yet found a solution as to how.

By using this code in PythonWin 1.5.2+ I get the following error:

NameError: isdigit

So I am assuming isdigit isn't supported in Python 1.5.2, is that correct? And if so, does anyone know any other ways to extract the numbers after #ADC: xxx ?

The Python 1.5.2p2 documentation is available online. Indeed, there is no isdigit in either str or in the module string .


Even in Python 1.5, str is a sequence that supports the in operation, so you could do:

def isdigit(c):
    return c in '0123456789'

pumpb = int(filter(isdigit, pump))

For more thorough parsing I'd use a regular expression, with module re instead; the code

import re
match = re.search('#ADC:\s*(\d+)', pump)
if match:
    number = match.group(1)

This will match #ADC: followed by any number of spaces, followed by 1 or more digits [0-9] ; the digits are captured in the group 1 , whose value is then stored to number if a match was found.

If the string is always exactly "#ADC: " , then simple string slicing should also work:

if pump[:6] == '#ADC: ':
    pumpb = int(pump[6:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM