Dr.Fykos
Dr.Fykos

Reputation: 90

python regex to replace part of string

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 A W North A W North A instead of 800 W North A

I don't understand what am I doing wrong. Would appreciate any help.

Thanks

Upvotes: 0

Views: 1340

Answers (2)

ryugie
ryugie

Reputation: 181

Like user92454 says, you want to use a space character, which is \s in Python regex.

You can use the pattern \s([A-Z\s]+) if you know the text you want to replace is always in caps. If not, you can use \s([A-z\s]+) (lower case 'z').

Upvotes: 0

user92454
user92454

Reputation: 1211

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.

Upvotes: 2

Related Questions