Python Forum

Full Version: filter out a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I use code like this
cpu_temp2 = os.popen("vcgencmd measure_temp").readline()
to get the cpu temperture of the pi.It returns a string temp=55.6'C
Now I want to get rid of the temp= and 'C so that I can insert just the number eg, 55.6 to a database. How do I get rid of temp= and 'C?
I tried re.sub("\D", "" cpu_temp2) but it returns 556, How do I preserver the 55.6?
Thanks
If you want to use a regular expression, use a positive one instead of a negative one:

Output:
>>> text = "temp=55.6'C" >>> import re >>> num_re = re.compile('\d+\.\d+') >>> match = num_re.search(text) >>> match.group() '55.6'
That one assumes there is always a digit after the decimal point, but you could modify it to not make that assumption. Of course, if the string is always of the same format, you know you don't want the first five characters or the last two characters. That can be solved just with slicing: cpu_temp2 = cpu_temp2[5:-2].
Thanks for the reply.
I found the second way is better, nice and succinct. And yes it ought to be the same format. Hopefully the cpu temp never reaches temp=123.4 'C :}
In the first method match.group(), some how python complains that in <module>
match.group()
AttributeError: 'NoneType' object has no attribute 'group'
Huh, the re didn't do that with me. That means there was no match, so num_re.search() returned None. Were you doing that with my example, or actual output of the temperature?

Note that the slicing method will still work for "temp=123.4'C". You still want to get rid of the first five characters and the last two, and that's what it does.
(Sep-14-2018, 12:27 PM)tony1812 Wrote: [ -> ]Thanks for the reply.
I found the second way is better, nice and succinct. And yes it ought to be the same format. Hopefully the cpu temp never reaches temp=123.4 'C :}
In the first method match.group(), some how python complains that in <module>
match.group()
AttributeError: 'NoneType' object has no attribute 'group'

Probably, occasionally you get a string with an integer temp value - changing RE to r'\d+(\.\d+)?' will solve that. (and you will be protected even against 123.4 'C Tongue )

PS I would suggest using subprocess.check_output instead of subprocess.popen.readline(). Of course, in that case RE method is preferred.