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

Hello,

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?
simpic
 
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
stranac
 
Posts: 1144
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]
'-0.3'

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

>>> ''.join(re.findall(r'[-.\d]', s))
'-0.3'
User avatar
snippsat
 
Posts: 221
Joined: Thu Feb 21, 2013 12:04 am


Return to General Coding Help

Who is online

Users browsing this forum: W3C [Linkcheck] and 2 guests

cron