Re.sub How To Do It In One Step?
I try to put this steps in one, but it doesnt work w = re.sub('[0-9]', r'9', w) w = re.sub('[A-Z]', r'X', w) w = re.sub('[a-z]', r'x', w) Does anybody knows how to make from such
Solution 1:
You may use a callback method as a replacement argument like this:
import re
rx = r'([0-9]+)|([A-Z]+)|[a-z]+'
w = "XXxxxx999"defrepl(m):
if m.group(1): # if ([0-9]) matchedreturn'9'# replace with 9elif m.group(2): # if ([A-Z]) matchedreturn'X'# replace with Xelse: # if ([a-z]) matchedreturn'x'# replace with xprint(re.sub(rx, repl, w)) # => Xx9See the Python demo.
The regex matches:
([0-9]+)- Group 1: 1+ digits|- or([A-Z]+)- Group 2: 1+ uppercase letters|- or[a-z]+- 1+ lowercase letters.
Post a Comment for "Re.sub How To Do It In One Step?"