how to extract numbers from a string

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
upymar
Posts: 18
Joined: Sat Feb 04, 2017 7:47 am

how to extract numbers from a string

Post by upymar » Sat Nov 02, 2019 10:21 pm

I'm trying to pass numbers from a received mqtt message to neopixel.

On my pc i got it to work with

Code: Select all

import re
msg = "rgb(124,95,8)"
r,g,b = re.findall('\d+',msg)
Unfortunately micropythons ure module doesn't know findall function.

Any Suggestionen?

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: how to extract numbers from a string

Post by kevinkk525 » Sun Nov 03, 2019 6:14 am

If you always get a message looking like that then it's easy:

r,g,b = msg[4:-1].split(",")

Not that r,g,b are still strings, so if you need int you'll have to convert them first.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: how to extract numbers from a string

Post by pythoncoder » Sun Nov 03, 2019 10:58 am

Note that r,g,b are still strings, so if you need int you'll have to convert them first.
For example by

Code: Select all

r, g, b = [int(x) for x in msg[4:-1].split(",")]
Peter Hinch
Index to my micropython libraries.

upymar
Posts: 18
Joined: Sat Feb 04, 2017 7:47 am

Re: how to extract numbers from a string

Post by upymar » Sun Nov 03, 2019 12:05 pm

Thank you, that works great!

Post Reply