Wednesday, 12 August 2015

Day 1 - regular expressions

I should know it before regular expressions are soooooo cool!!

here is a peace of code from "Dive into Python"

>>> s = '100 NORTH MAIN ROAD' >>> s.replace('ROAD', 'RD.') '100 NORTH MAIN RD.' >>> s = '100 NORTH BROAD ROAD' >>> s.replace('ROAD', 'RD.') '100 NORTH BRD. RD.' >>> s[:-4] + s[-4:].replace('ROAD', 'RD.') '100 NORTH BROAD RD.' >>> import re >>> re.sub('ROAD$', 'RD.', s) # first what we are replacing, second the replacement and the last one from which string '100 NORTH BROAD RD.'


BUT WHAT TO DO IF: s = '100 BROAD' which means that the code will give us >>>100 BRD
and that is not what I want


re.sub(r'\bROAD\b', 'RD.', s)

this peace of coad will take only text of ROAD with two spaces from each side that is why we have '\b' and r give us raw string and I have now idea what means raw string, but I WILL KNOW SOOOON!!

No comments:

Post a Comment