Very simple question but I can't seem to figure it out.
The following code:
import re
addr = '800 W NORTH AVE'
re.sub(r'([a-zA-Z]+)', 'W North A', addr)
It gives me as a result 800 W North AW North AW North A instead of 800 W North A
I don't understand what am I doing wrong. Would appreciate any help.
Thanks
You are not matching the space character. This makes every word get replaced with the replace string. You need something like this instead:
re.sub(r'(([a-zA-Z]+\?)+)', 'W North A', addr)
This matches one or more of a word followed by one or more spaces.
Like user92454 says, you want to use a space character, which is \\s
in Python regex.
You can use the pattern \\s([AZ\\s]+)
if you know the text you want to replace is always in caps. If not, you can use \\s([Az\\s]+)
(lower case 'z').
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.