nautilus27
Posts: 72
Joined: Fri May 22, 2015 9:38 pm

Extracting numbers from series of numbers

Sat Jul 30, 2016 4:27 pm

OK, so i need to extract certain numbers from the data coming from the bluetooth rfcomm. The data flows continuously. And it contains float numbers that are seperated by commas like: "14.26,03.41,0.2"

What I want to do is to create 3 variables, convert these values from float to integer and then make the variables carry these values.
Like Variable X = 14
Y = 03
Z =0

I could do it in Arduino but Python is another world for me. Anyone experienced with number operations, conversion and filtering in Python would like to lend me a hand?

SonOfAMotherlessGoat
Posts: 690
Joined: Tue Jun 16, 2015 6:01 am

Re: Extracting numbers from series of numbers

Sat Jul 30, 2016 5:30 pm

Do you need the leading zero's? You could split on the "," and then index the list to your variables, converting to int on the way.
Account Inactive

nautilus27
Posts: 72
Joined: Fri May 22, 2015 9:38 pm

Re: Extracting numbers from series of numbers

Sat Jul 30, 2016 5:36 pm

SonOfAMotherlessGoat wrote:Do you need the leading zero's? You could split on the "," and then index the list to your variables, converting to int on the way.
It's not about zeros actually. My input will produce floats starting from 0.0 to 99.9. I can omit the value after the dot it doesn't matter. But as I stated in my first post, there are 3 different kind of floats in there seperated by commas. I need a solution that splits these values by the commas.

User avatar
joan
Posts: 14748
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Extracting numbers from series of numbers

Sat Jul 30, 2016 5:37 pm

Perhaps use Python split?

SonOfAMotherlessGoat
Posts: 690
Joined: Tue Jun 16, 2015 6:01 am

Re: Extracting numbers from series of numbers

Sat Jul 30, 2016 5:42 pm

Yep, split will do it. Returns a list. Only sticky thing may be with the integer conversion. May have to wrap it as a

Code: Select all

int(float(var))
Account Inactive

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Extracting numbers from series of numbers

Sun Jul 31, 2016 6:32 am

So, pulling all of the above posts together, you could do this:

Code: Select all

line = "14.26,03.41,0.2" 

x, y, z = (int(float(n)) for n in line.split(","))

print("X: {x}\tY: {y}\tZ: {z}".format(x=x, y=y, z=z))
which should output

Code: Select all

X: 14	Y: 3	Z: 0
NB this only works assuming you've got 3 values in your line. If not, you'll get a ValueError.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”