regex to strip °C from a string

This is the place for queries that don't fit in any of the other categories.

regex to strip °C from a string

Postby simpic » Sat Jan 11, 2014 6:50 pm


need some assistance on a regex to strip '°C' from a value which may contain a minus figure such as '-0.3 °C'

My script currently uses re.sub(r'[^0-9\-\d.]',' ', temp) where temp is the value but it strips the - as well.

Can someone help?
Posts: 4
Joined: Fri Jan 10, 2014 10:13 am

Re: regex to strip °C from a string

Postby stranac » Sat Jan 11, 2014 6:59 pm

If you just need to remove '°C', just do that:
Code: Select all
>>> '-0.3 °C'.replace('°C', '')
'-0.3 '

Btw, your regex should not be touching the '-' at all...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

Re: regex to strip °C from a string

Postby snippsat » Sat Jan 11, 2014 8:53 pm

Code: Select all
>>> s = '-0.3 °C'
>>> s.split()[0]

>>> import re
>>> re.sub(r'\s.*', '', s)

>>> ''.join(re.findall(r'[-.\d]', s))
We will be moving to on October 1 2016
User avatar
Posts: 1251
Joined: Thu Feb 21, 2013 12:04 am

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 5 guests