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