Python Forum
Remove Parts of a String - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Remove Parts of a String (/thread-199.html)



Remove Parts of a String - Dean Stackhouse - Sep-29-2016

Hello,

I'm quite new to python and am attempting to do some coding on a Raspberry Pi.

I have a sensor that gives an output in the following format.

628.6,339,0.30,1.000


I need to splice it so it just gives me the 628.6

The string isn't always the same length so i need to chop it on the first comma.

I also need to change the decimal point so it looks like this but that should be easy enough once its just a number.

6.286

Thanks


RE: Remove Parts of a String - j.crater - Sep-29-2016

Hello Dean, I believe you have a couple of options available. You can do:

some_string = "628.6,339,0.30,1.000"
split_string = some_string.split(',')
split_string is now a list of strings:
['628.6', '339', '0.30', '1.000']
So you need the first element of this list:

first_element = split_string[0]
At this point first_element is still a string, but you can convert it to a float and do arithmetics with it.


RE: Remove Parts of a String - wavic - Sep-29-2016

Or you can get the first element of returned list at once with split

first_element = some_string.split(',')[0]



RE: Remove Parts of a String - Dean Stackhouse - Sep-29-2016

Thanks j.crater for the solution and thanks wavic for compressing the code.

I ended up using the following line to query my EC sensor and convert the output to from μS/cm to CF

output = float(AtlasI2C().query('r').split(',')[0])/100


RE: Remove Parts of a String - Kebap - Sep-29-2016

Thanks for reporting back and again welcome to Python! :)


RE: Remove Parts of a String - wavic - Sep-29-2016

It's not about compressing the code. It's about how Python works. I just start to clear it for myself.
Welcome!